LeetCode167. Two Sum II - Input array is sorted(双指针)

Posted SomnusMistletoe

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode167. Two Sum II - Input array is sorted(双指针)相关的知识,希望对你有一定的参考价值。

题意:对于一个有序数组,输出和为target的两个元素的下标。题目保证仅有唯一解。

分析:

法一:二分。枚举第一个元素,二分找另一个元素,时间复杂度O(nlogn),非最优解。

class Solution {
public:
    vector<int> twoSum(vector<int>& numbers, int target) {
        int len = numbers.size();
        vector<int> ans;
        for(int i = 0; i < len; ++i){
            int tmp = target - numbers[i];
            int l = i + 1;
            int r = len - 1;
            bool ok = false;
            while(l <= r){
                int mid = l + (r - l) / 2;
                if(numbers[mid] == tmp){
                    ok = true;
                    ans.push_back(i + 1);
                    ans.push_back(mid + 1);
                    break;
                }
                else if(numbers[mid] < tmp){
                    l = mid + 1;
                }
                else{
                    r = mid - 1;
                }
            }
            if(ok){
                break;
            }
        }
        return ans;
    }
};

法二:双指针,head和tail分别指向数组中头尾元素,若numbers[head]+numbers[tail]>target,则tail--;若numbers[head]+numbers[tail]<target,则head++;直到numbers[head]+numbers[tail]==target。时间复杂度O(n)。

class Solution {
public:
    vector<int> twoSum(vector<int>& numbers, int target) {
        vector<int> ans;
        int head = 0;
        int tail = numbers.size() - 1;
        while(head < tail){
            int sum = numbers[head] + numbers[tail];
            if(sum == target){
                ans.push_back(head + 1);
                ans.push_back(tail + 1);
                break;
            }
            else if(numbers[head] + numbers[tail] < target) ++head;
            else --tail;
        }
        return ans;
    }
};

  

以上是关于LeetCode167. Two Sum II - Input array is sorted(双指针)的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode167. Two Sum II - Input array is sorted

LeetCode 167. Two Sum II - Input array is sorted

[LeetCode] 167. Two Sum II - Input array is sorted

LeetCode:167. Two Sum II - Input array is sorted

Leetcode #167. Two Sum II - Input array is sorted

Leetcode167. Two Sum II - Input array is sorted