File tree Expand file tree Collapse file tree 1 file changed +43
-0
lines changed Expand file tree Collapse file tree 1 file changed +43
-0
lines changed Original file line number Diff line number Diff line change
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
+ };
You can’t perform that action at this time.
0 commit comments