Sword finger offer interview question 57. Two numbers with sum s [simple]-unordered_map, double pointer

My solution:

1. The first idea is the first question of LeetCode, the sum of two numbers, also used unordered_map

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

2. It should be noted that this is an incremental array, you can use the double pointer Dafa

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        int i=0,j=nums.size()-1;
        vector<int> res;
        while(i<j){
            if(nums[i]+nums[j]==target){
                res.push_back(nums[i]);
                res.push_back(nums[j]);
                return res;
            }
            else if(nums[i]+nums[j]<target)    i++;
            else    j--;
        }
        return res;
    }
};

 

Published 65 original articles · Like1 · Visits 492

Guess you like

Origin blog.csdn.net/qq_41041762/article/details/105451431