美文网首页Leetcode
Leetcode 167. Two Sum II - Input

Leetcode 167. Two Sum II - Input

作者: SnailTyan | 来源:发表于2019-01-31 15:39 被阅读0次

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

    1. Description

    Two Sum II - Input array is sorted

    2. Solution

    • Version 1
    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;
        }
    };
    
    • Version 2
    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/

    相关文章

      网友评论

        本文标题:Leetcode 167. Two Sum II - Input

        本文链接:https://www.haomeiwen.com/subject/bhaksqtx.html