Skip to content

Commit 96c5699

Browse files
author
applewjg
committed
Update TwoSum.h
1 parent 9be0d55 commit 96c5699

File tree

1 file changed

+9
-22
lines changed

1 file changed

+9
-22
lines changed

TwoSum.h

Lines changed: 9 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
Date: Jan 17, 2013
44
Update: Jan 16, 2014
55
Problem: Two Sum
6-
Difficulty: easy
6+
Difficulty: Medium
77
Source: http://oj.leetcode.com/problems/two-sum/
88
Notes:
99
Given an array of integers, find two numbers such that they add up to a specific target number.
@@ -54,29 +54,16 @@ class Solution {
5454
return res;
5555
}
5656

57-
typedef unordered_map<int, vector<int> > MAP;
58-
5957
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});
7465
}
75-
76-
vector<int> res;
77-
res.push_back(min(index1, index2));
78-
res.push_back(max(index1, index2));
79-
return res;
8066
}
67+
return vector<int>();
8168
}
8269
};

0 commit comments

Comments
 (0)