leecode first question (Two Sum)

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {  
        map<int, int> hash_table; //Create a hash table
        vector<int> index;  
        for(int i = 0; i < nums.size(); ++i){  
            if (hash_table.count(nums.at(i))){ //if exists
                int n = hash_table.at(nums.at(i)); //put the value Find the corresponding position
                index.push_back(n);  
                index.push_back(i);  
                break;  
            }  
            int f=target - nums.at(i);   
             hash_table.insert(make_pair(f, i)); //The value of Insert into hash table
      
    }   
        return index;    
    }

};


The idea is to find the same value in the table, and if you can't find it, insert your own complement into the hash table, which should be the solution with the lowest time complexity.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325544217&siteId=291194637