167. Two Sum II - Input array is sorted
Easy
804337FavoriteShare
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.
这道题也悲剧地重写了,没有考虑负数的情况。重写的时候用了暴力法,几分钟搞定了。看来暴力法有时是首选!
先贴AC的代码:
class Solution {
public:
vector<int> twoSum(vector<int>& numbers, int target) {
vector<int> ans;
ans.clear();
for(int i=0;i<numbers.size()-1;i++)
{
int j=i+1;
while(j<numbers.size())
{
if(numbers[i]+numbers[j]==target)
{
ans.push_back(i+1);
ans.push_back(j+1);
return ans;
}
j++;
}
}
vector<int> ans0;
ans0.clear();
return ans0;
}
};
下面是没有考虑负数情况的代码,最近二分法看多了,还使用了二分法,把一道easy的题搞得那么复杂,最后还不能AC。纪念一下:
vector<int> twoSum(vector<int>& numbers, int target) {
vector<int> ans;
vector<int> ans0;
ans0.clear();
int L = 0;
int R = numbers.size() - 1;
int mid;
while (L<R)
{
mid = L + (R - L) / 2;
if (numbers[mid]<target)L = mid + 1;
else R = mid;
}
//ans.push_back(L);//L是正好比target小的
int i = L;
int j = 0;
while ((i>j) && (i >= 0) && (j<L))
{
if ((numbers[i] + numbers[j]) == target)
{
ans.push_back(j + 1);
ans.push_back(i + 1);
return ans;
}
else if ((numbers[i] + numbers[j])>target)
{
i--;
}
else
{
j++;
}
}
return ans0;
}