LeetCode-167 number two. Sum II

Description
Here Insert Picture Description
Analysis
(1) hashing (dichotomy may first locate the largest element below the target value before the hash)
(2) use of the characteristics of the array in ascending order, using the double pointer method. Start pointer points to the next subscript 0 0 , the termination of the last element pointer to an array. When the two elements of the pointer is equal to the target and return; if it exceeds, the tail pointer minus one; if less than the first pointer plus one. Fantastic.

Code
Hash

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

Double pointer

class Solution {
public:
    vector<int> twoSum(vector<int>& numbers, int target) {
        vector<int> res;
        int start = 0, end = numbers.size() - 1;
        while(start < end){
            int temp = numbers[start] + numbers[end];
            if(temp == target){
                return {start + 1, end + 1};
            }
            if(temp > target) end -= 1;
            else start += 1;
        }
        return {-1, -1};
    }
};
He published 189 original articles · won praise 107 · views 70000 +

Guess you like

Origin blog.csdn.net/cprimesplus/article/details/103338021