240
笔下虽有千言,胸中实无一策

30 Day Challenge Day 14 | Leetcode 167. Two Sum II - Input array is sorted

题解

Easy | Hashmap

class Solution {
public:
    vector<int> twoSum(vector<int>& numbers, int target) {
        unordered_map<int, int> m;
        for(int i = 0; i < numbers.size(); i++) {
            if(m.count(target - numbers[i])) {
                return {m[target-numbers[i]]+1, i+1};
            }
            m[numbers[i]] = i;
        }
        return {-1, -1};
    }
};

Easy | Two Pointers

因为原数组是排过序的,因此可以想到用双指针法,即左右缩进。

class Solution {
public:
    vector<int> twoSum(vector<int>& numbers, int target) {
        int low = 0, high = numbers.size() - 1;
        while (low < high) {
            int sum = numbers[low] + numbers[high];
            if (sum == target)
                return {low + 1, high + 1};
            else if (sum < target)
                ++low;
            else
                --high;
        }
        return {-1, -1};
    }
};
posted @ 2020-09-29 13:31  CasperWin  阅读(46)  评论(0编辑  收藏  举报