Tuesday, August 2, 2016

1. Two Sum

I was trying to sort the number and find the two sum index by binary search. However, this is completely wrong. Since we need to return the index, we shouldn't sort the array because by doing this the index is changed. So I used hash map to solve the problem.

1:  class Solution {  
2:  public:  
3:    vector<int> twoSum(vector<int>& nums, int target) {  
4:      unordered_map<int, int> hash;  
5:      vector<int> res;  
6:      for (int i = 0; i < nums.size(); i++) {  
7:        int t = target - nums[i];  
8:        if (hash.find(t) != hash.end()) {  
9:          res.push_back(i);  
10:          res.push_back(hash[t]);  
11:          break;  
12:        }  
13:        hash[nums[i]] = i;  
14:      }  
15:      return res;  
16:    }  
17:  };  

No comments:

Post a Comment