leetcode167:两数之和 II - 输入有序数组,不再做辣鸡大王,双指针解法(效果一般)

leetcode167:两数之和 II - 输入有序数组,不再做辣鸡大王,双指针解法(效果一般)_第1张图片
因为有序排列所以

小于目标值时,++小数

大于目标值时,–大数

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

            }
            else{
                --high;
            }
        }
        return loc;

    }
};

你可能感兴趣的:(leetcode)