|
3 | 3 | Date: Jan 17, 2013
|
4 | 4 | Update: Jan 16, 2014
|
5 | 5 | Problem: Two Sum
|
6 |
| - Difficulty: easy |
| 6 | + Difficulty: Medium |
7 | 7 | Source: http://oj.leetcode.com/problems/two-sum/
|
8 | 8 | Notes:
|
9 | 9 | Given an array of integers, find two numbers such that they add up to a specific target number.
|
@@ -54,29 +54,16 @@ class Solution {
|
54 | 54 | return res;
|
55 | 55 | }
|
56 | 56 |
|
57 |
| - typedef unordered_map<int, vector<int> > MAP; |
58 |
| - |
59 | 57 | vector<int> twoSum_2(vector<int> &numbers, int target) {
|
60 |
| - MAP map; |
61 |
| - for (int i = 0; i < numbers.size(); ++i) |
62 |
| - map[numbers[i]].push_back(i+1); |
63 |
| - |
64 |
| - for (int i = 0; i < numbers.size(); ++i) |
65 |
| - { |
66 |
| - MAP::iterator it = map.find(target - numbers[i]); |
67 |
| - if (it == map.end()) continue; |
68 |
| - |
69 |
| - int index1 = it->second[0], index2 = i + 1; |
70 |
| - |
71 |
| - if (numbers[i] == target - numbers[i]) { // two elements are the same |
72 |
| - if (it->second.size() == 1) continue; |
73 |
| - index2 = it->second[1]; |
| 58 | + unordered_map<int, int> hash; |
| 59 | + for (int i = 0; i < numbers.size(); ++i) { |
| 60 | + int second = target - numbers[i]; |
| 61 | + if (hash.find(second) != hash.end()) { |
| 62 | + return vector<int>{hash[res]+1, i+1}; |
| 63 | + } else { |
| 64 | + hash.insert(pair<int, int>{numbers[i],i}); |
74 | 65 | }
|
75 |
| - |
76 |
| - vector<int> res; |
77 |
| - res.push_back(min(index1, index2)); |
78 |
| - res.push_back(max(index1, index2)); |
79 |
| - return res; |
80 | 66 | }
|
| 67 | + return vector<int>(); |
81 | 68 | }
|
82 | 69 | };
|
0 commit comments