File tree Expand file tree Collapse file tree 2 files changed +66
-0
lines changed Expand file tree Collapse file tree 2 files changed +66
-0
lines changed Original file line number Diff line number Diff line change 1+ //1. using map
2+ //2. using set : why? It doesn't have to use a pair of key and value.
3+
4+ class Solution {
5+ public boolean containsDuplicate (int [] nums ) {
6+ //Map<Integer, Boolean> appearance = new HashMap<>();
7+ Set <Integer > appearance = new HashSet <>();
8+
9+ for (int i =0 ; i <nums .length ; i ++)
10+ {
11+ if (appearance .contains (nums [i ]))
12+ {
13+ return true ;
14+ }
15+ else
16+ {
17+ appearance .add (nums [i ]);
18+ }
19+ }
20+
21+ return false ;
22+ }
23+ }
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