167兩數之和 II - 輸入有序數組(雙指針)

1、題目描述

給定一個已按照升序排列 的有序數組,找到兩個數使得它們相加之和等於目標數。

函數應該返回這兩個下標值 index1 和 index2,其中 index1 必須小於 index2。

說明:

返回的下標值(index1 和 index2)不是從零開始的。
你可以假設每個輸入只對應唯一的答案,而且你不可以重複使用相同的元素。

2、示例

輸入: numbers = [2, 7, 11, 15], target = 9
輸出: [1,2]
解釋: 2 與 7 之和等於目標數 9 。因此 index1 = 1, index2 = 2 。

3、題解

基本思想:雙指針

#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
class Solution {
public:
	vector<int> twoSum(vector<int>& numbers, int target) {
		int left = 0, right = numbers.size() - 1, sum;
		while (left < right)
		{
			sum = numbers[left] + numbers[right];
			if (sum == target)
				return { left + 1, right + 1 };
			else if (sum > target)
				right--;
			else
				left++;
		}
		return {-1, -1};
	}
};
int main()
{
	Solution solute;
	vector<int> numbers = { 2, 7, 11, 15 };
	int target = 9;
	vector<int> res = solute.twoSum(numbers, target);
	for_each(res.begin(), res.end(), [](const int v) {cout << v << endl; });
	return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章