LeetCode#167 Two Sum II - Input Array is Sorted

1、这在之前的的基础上更好做一点。前面的问题需要查表,这里直接在原数组上就可以了——二分。对于待查数据,使用二分缩小区间直至找到,是很好的算法。
2、更精妙的方法是双指针,头尾两个指针,相加和大了,则尾指针后移,和小了就首指针前移,直到确定两个数的位置。

class Solution {
public:
    vector<int> twoSum(vector<int>& numbers, int target) {
        int length = numbers.size();
        int ptrLeft = 0;
        int ptrRight = length - 1;
        int cache = numbers[ptrLeft] + numbers[ptrRight];
        while(cache != target){
            cache = numbers[ptrLeft] + numbers[ptrRight];
            if(cache < target)
                ptrLeft++;
            else if(cache > target)
                ptrRight--;
        }

        return {ptrLeft+1, ptrRight+1};
    }
};
class Solution {
public:
    vector<int> twoSum(vector<int>& numbers, int target) {
        int length = numbers.size();
        int ptrLeft = 0;
        int ptrRight = length - 1;
        for(int i = 0; i < length; i++){
            ptrLeft = i + 1;
            while(ptrLeft <= ptrRight){
                int ptr = (ptrLeft + ptrRight) / 2;
                if(numbers[ptr] == target - numbers[i]){
                    return {i+1, ptr+1};
                }
                else if(numbers[ptr] < target - numbers[i])
                    ptrLeft = ptr+1;
                else if(numbers[ptr] > target - numbers[i])
                    ptrRight = ptr-1;

            }
        }

        return {0, 0};
    }
};

猜你喜欢

转载自blog.csdn.net/rpybd/article/details/82432016