167 - Two Sum II - Input array is sorted

解法一 - Two Pointer

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        if(nums.size() < 2) return {};

        int l = 0, r = nums.size()-1;
        while(l <= r) {
            if(nums[l] + nums[r] == target) {
                return {l+1, r+1};
            }
            else if(nums[l] + nums[r] > target) r--;
            else if(nums[l] + nums[r] < target) l++;
        }

        return {};
    }
};

results matching ""

    No results matching ""