Skip to content

Commit 4e46337

Browse files
authored
[JinuCheon] Week 01 solutions (#2668)
* 217. Contains Duplicate * Two Sum
1 parent 1ff1969 commit 4e46337

2 files changed

Lines changed: 64 additions & 0 deletions

File tree

contains-duplicate/JinuCheon.java

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
import java.util.HashSet;
2+
import java.util.Set;
3+
4+
class Solution {
5+
/**
6+
* 79/79 cases passed (19 ms)
7+
* Your runtime beats 32.04 % of java submissions
8+
* Your memory usage beats 6.16 % of java submissions (108.1 MB)
9+
*
10+
* When I changed HashSet to LinkedHashSet, the runtime and memory usage increased a little bit.
11+
*
12+
* Improvement:
13+
* if (!set.add(num)) return true; // when num is already in the set, return true.
14+
* It looks like more simple.
15+
*/
16+
public boolean containsDuplicate(int[] nums) {
17+
Set<Integer> exist = new HashSet<>();
18+
19+
for (int num : nums) {
20+
if (exist.contains(num)) {
21+
return true;
22+
} else {
23+
exist.add(num);
24+
}
25+
}
26+
return false;
27+
}
28+
}

two-sum/JinuCheon.java

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
// Follow-up: Can you come up with an algorithm that is less than O(n2) time complexity?
2+
// O(n2)
3+
// class Solution1 {
4+
// public int[] twoSum(int[] nums, int target) {
5+
// int size = nums.length;
6+
// for (int i=0; i<size; i++) {
7+
// for (int j=0; j<size; j++) {
8+
// if (i==j) continue;
9+
// if (nums[i] + nums[j] == target) {
10+
// return new int[]{i, j};
11+
// }
12+
// }
13+
// }
14+
// throw new IllegalArgumentException();
15+
// }
16+
// }
17+
18+
19+
// I spent almost 20m thinking about this, but couldn't come up any ideas.
20+
// Finally I asked to LLM, there was a crazy solution.
21+
class Solution {
22+
public int[] twoSum(int[] nums, int target) {
23+
Map<Integer, Integer> map = new HashMap<>();
24+
25+
for (int i = 0; i < nums.length; i++) {
26+
int pair = target - nums[i];
27+
28+
if (map.containsKey(pair)) {
29+
return new int[]{i, map.get(pair)};
30+
}
31+
32+
map.put(nums[i], i);
33+
}
34+
throw new IllegalArgumentException();
35+
}
36+
}

0 commit comments

Comments
 (0)