Skip to content

Commit 578de07

Browse files
committed
two-sum
1 parent f9870c8 commit 578de07

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

two-sum/mkwkw.cpp

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
//Store the number and the index.
2+
//There can be only 2 same numbers. <- there is exactly one solution
3+
4+
class Solution {
5+
public:
6+
vector<int> twoSum(vector<int>& nums, int target) {
7+
8+
map<int, vector<int>> numAndIndex;
9+
vector<int> answer;
10+
11+
//map: key:nums[i], value:{indexs}
12+
for(int i=0; i<nums.size(); i++)
13+
{
14+
numAndIndex[nums[i]].push_back(i);
15+
}
16+
17+
for(int i=0; i<nums.size()-1; i++)
18+
{
19+
if(numAndIndex.contains(target-nums[i]))
20+
{
21+
//To pick another number, not own number
22+
if(target-nums[i]==nums[i]&&numAndIndex[nums[i]].size()==2)
23+
{
24+
answer.push_back(numAndIndex[nums[i]][0]);
25+
answer.push_back(numAndIndex[nums[i]][1]);
26+
}
27+
else if(target-nums[i]!=nums[i])
28+
{
29+
answer.push_back(numAndIndex[nums[i]][0]);
30+
answer.push_back(numAndIndex[target-nums[i]][0]);
31+
}
32+
}
33+
34+
if(answer.size()==2)
35+
{
36+
break;
37+
}
38+
}
39+
40+
return answer;
41+
42+
}
43+
};

0 commit comments

Comments
 (0)