Skip to content

Commit 5e35fcb

Browse files
authored
Merge pull request #1677 from mkwkw/main
[mkwkw] WEEK 01 Solutions
2 parents 4e124bc + 578de07 commit 5e35fcb

File tree

2 files changed

+66
-0
lines changed

2 files changed

+66
-0
lines changed

contains-duplicate/mkwkw.java

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
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+
}

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)