LeetCode刷题笔记--167. Two Sum II - Input array is sorted

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 twoSum(vector& numbers, int target) {
        vector ans;
        ans.clear();
        for(int i=0;i         {
            int j=i+1;
            while(j             {
                if(numbers[i]+numbers[j]==target)
                {
                    ans.push_back(i+1);
                    ans.push_back(j+1);
                    return ans;
                }
                j++;
            }
        }
        vector ans0;
        ans0.clear();
        return ans0;
        
    }

    
};

下面是没有考虑负数情况的代码,最近二分法看多了,还使用了二分法,把一道easy的题搞得那么复杂,最后还不能AC。纪念一下:

vector twoSum(vector& numbers, int target) {
    vector ans;
    vector ans0;
    ans0.clear();
    int L = 0;
    int R = numbers.size() - 1;
    int mid;
    while (L     {
        mid = L + (R - L) / 2;
        if (numbers[mid]         else R = mid;
    }
    //ans.push_back(L);//L是正好比target小的
    int i = L;
    int j = 0;
    
    while ((i>j) && (i >= 0) && (j     {
        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;
}

你可能感兴趣的:(LeetCode刷题笔记--167. Two Sum II - Input array is sorted)