leetcode 167. 两数之和 II - 输入有序数组

leetcode 167. 两数之和 II - 输入有序数组

答案一:用例全部通过,但是超时。朴实的两层循环

class Solution {
public:
    vector<int> twoSum(vector<int>& numbers, int target) {
        vector<int> result;
        for (int i = 0; i < numbers.size(); i++) {
            int ans = target - numbers[i];
            int j = 0;
            for (j = i+1; (j < numbers.size()) && (numbers[j] < ans); j++){
                ;
            }

            if ((j < numbers.size()) && (numbers[j] == ans)) {
                result.push_back(i+1);
                result.push_back(j+1);
                break;
            }
        }
        return result;
    }
};

答案二:双指针:头、尾指针

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

你可能感兴趣的:(leetcode,双指针,leetcode,算法)