Leetcode 167. Two Sum II - Input array is sorted

文章作者:Tyan
博客:noahsnail.com  |  CSDN  | 

1. Description

Leetcode 167. Two Sum II - Input array is sorted_第1张图片
Two Sum II - Input array is sorted

2. Solution

  • Version 1
class Solution {
public:
    vector twoSum(vector& numbers, int target) {
        int size = numbers.size();
        vector result;
        for(int i = 0; i < size - 1; i++) {
            for(int j = i + 1; j < size; j++) {
                if(numbers[i] + numbers[j] == target) {
                    result.push_back(i + 1);
                    result.push_back(j + 1);
                    return result;
                }
            }
        }
        return result;
    }
};
  • Version 2
class Solution {
public:
    vector twoSum(vector& numbers, int target) {
        int size = numbers.size();
        vector result;
        for(int i = 0; i < size - 1; i++) {
            int other = binarySearch(numbers, i + 1, size - 1, target - numbers[i]);
            if(other != - 1) {
                result.push_back(i + 1);
                result.push_back(other + 1);
                return result;
            }
        }
        return result;
    }

private:
    int binarySearch(vector& numbers, int left, int right, int target) {
        while(left <= right) {
            int middle = (left + right) / 2;
            if(numbers[middle] == target) {
                return middle;
            }
            else if(numbers[middle] > target) {
                right = middle - 1;
            }
            else {
                left = middle + 1;
            }
        }
        return -1;
    }
};

Reference

  1. https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/description/

你可能感兴趣的:(Leetcode 167. Two Sum II - Input array is sorted)