题目:
Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to a specific target number.
The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2.
Note:
- Your returned answers (both index1 and index2) are not zero-based.
- You may assume that each input would have exactly one solution and you may not use the same element twice.
Example:
Input: numbers = [2,7,11,15], target = 9 Output: [1,2] Explanation: The sum of 2 and 7 is 9. Therefore index1 = 1, index2 = 2.
解题思路:
这道题的目标是找到升序数组中的两个元素索引,两个元素的和等于目标值target。将两个变量变为一个定量一个变量。索引一idx1从最左边开始扫描,设定sum的值为numbers[idx1],索引二idx2从数组的末尾开始扫描,如果numbers[idx1] + numbers[idx2]小于target,则说明以idx1为开始的所有组合都小于target,更新idx1的坐标,重新继续扫描。
题目的另一个坑是存在重复元素,需要在每次进行idx2遍历前,确定numbers[idx1]没有出现过。
代码:
public:
vector<int> twoSum(vector<int>& numbers, int target) {
vector<int> res(2, 0);
bool flag = true;
for(int i = 0; i < numbers.size() && flag; i++)
{
if(i == 0 || (i > 0 && numbers[i] != numbers[i-1]))
{
int sum = numbers[i];
for(int j = numbers.size() - 1; j > i; j--)
{
if(sum + numbers[j] < target)
break;
if(sum + numbers[j] == target)
{
res[0] = i + 1;
res[1] = j + 1;
flag = false;
break;
}
}
}
}
return res;
}
Leetcode的实测效率大于99%+!^__________________________________^