Leetcode

Leetcode 167. Two Sum II - Input

2019-01-31  本文已影响0人  SnailTyan

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

1. Description

Two Sum II - Input array is sorted

2. Solution

class Solution {
public:
    vector<int> twoSum(vector<int>& numbers, int target) {
        int size = numbers.size();
        vector<int> 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;
    }
};
class Solution {
public:
    vector<int> twoSum(vector<int>& numbers, int target) {
        int size = numbers.size();
        vector<int> 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<int>& 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/
上一篇下一篇

猜你喜欢

热点阅读