有序数组求两个数的和为某个值O(n)解法

class Solution {
public:
    vector<int> twoSum(vector<int>& numbers, int target) {
        int len = numbers.size();
        int i = 0, j = len - 1;
        vector<int> ans;
        while (numbers[i] + numbers[j] != target)
        {
            if (numbers[i] + numbers[j] < target)
            {
                ++i;
                continue;
            }
            if (numbers[i] + numbers[j] > target)
            {
                --j;
                continue;
            }
        }
        ans.push_back(i + 1);
        ans.push_back(j + 1);
        return ans;
    }
};

点赞