[LeetCode] 167. Two Sum II - Input array is sorted
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.
从numbers中找两数之和为target,返回下标
这道题我是通过Binary Search的标签进入的,所以想都没想直接写了,最后虽然AC了但成绩并不好,都是菜鸟的借口
int binarySearch(vector<int>& vec, int low, int high, int target)
{
while (low <= high)
{
int mid = (low + high) / 2;
if (vec[mid] == target)
{
return mid;
}
else if (vec[mid] > target)
{
high = mid-1;
}
else if (vec[mid] < target)
{
low = mid + 1;
}
}
return -1;
}
vector<int> twoSum(vector<int>& numbers, int target) {
for (int i = 0; i < numbers.size()-1; i++)
{
int rest = target - numbers[i];
int index = binarySearch(numbers, i+1, numbers.size(), rest);
if (index != -1)
{
return vector<int> {i+1, index+1};
}
}
}
题目说了,vector是排好序的,所以可以更快找到答案
用low和high指向numbers的两端,low++使两数之和增加,high--使两束之和减少,逐渐逼近target
vector<int> twoSum(vector<int>& numbers, int target) {
vector<int> result;
int low = 0;
int high = numbers.size() - 1;
while (low <= high)
{
int sum = numbers[low] + numbers[high];
if (sum == target)
{
return vector<int> {low + 1, high + 1};
}
else if (sum > target)
{
high--;
}
else if (sum < target)
{
low++;
}
}
}