Skip to content

Commit 94aa3a2

Browse files
authored
Merge pull request #1158 from sm9171/main
[sm9171] Week01 Solutions
2 parents a2d1e52 + 6df5759 commit 94aa3a2

File tree

5 files changed

+83
-0
lines changed

5 files changed

+83
-0
lines changed

contains-duplicate/sm9171.java

+13
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
class Solution {
2+
public boolean containsDuplicate(int[] nums) {
3+
HashSet<Integer> set = new HashSet<>();
4+
5+
for (int i = 0; i < nums.length; i++) {
6+
if (set.contains(nums[i])) {
7+
return true;
8+
}
9+
set.add(nums[i]);
10+
}
11+
return false;
12+
}
13+
}

house-robber/sm9171.java

+14
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
class Solution {
2+
public int rob(int[] nums) {
3+
if (nums.length == 0) return 0;
4+
if (nums.length == 1) return nums[0];
5+
6+
nums[1] = Math.max(nums[0], nums[1]);
7+
8+
for (int i = 2; i < nums.length; i++) {
9+
nums[i] = Math.max(nums[i - 1], nums[i - 2] + nums[i]);
10+
}
11+
12+
return nums[nums.length - 1];
13+
}
14+
}
+20
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
class Solution {
2+
public int longestConsecutive(int[] nums) {
3+
int longest = 0;
4+
Set<Integer> set = Arrays.stream(nums)
5+
.boxed()
6+
.collect(Collectors.toSet());
7+
8+
for (Integer i : set) {
9+
if (set.contains(i - 1)) continue;
10+
int length = 1;
11+
12+
while (set.contains(i + 1)) {
13+
length++;
14+
i++;
15+
}
16+
longest = Math.max(longest, length);
17+
}
18+
return longest;
19+
}
20+
}

top-k-frequent-elements/sm9171.java

+21
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
class Solution {
2+
public static int[] topKFrequent(int[] nums, int k) {
3+
Map<Integer, Integer> hashMap = new HashMap<>();
4+
for (int i = 0; i < nums.length; i++) {
5+
int num = nums[i];
6+
hashMap.put(num, hashMap.getOrDefault(num, 0) + 1);
7+
}
8+
9+
List<Integer> list = hashMap.entrySet().stream()
10+
.sorted(Map.Entry.<Integer, Integer>comparingByValue().reversed())
11+
.limit(k)
12+
.map(Map.Entry::getKey)
13+
.toList();
14+
15+
int[] result = list.stream()
16+
.mapToInt(Integer::intValue)
17+
.toArray();
18+
19+
return result;
20+
}
21+
}

two-sum/sm9171.java

+15
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
class Solution {
2+
public int[] twoSum(int[] nums, int target) {
3+
Map<Integer, Integer> hashMap = new HashMap<>();
4+
5+
for (int i = 0; i < nums.length; i++) {
6+
int gap = target - nums[i];
7+
if(hashMap.containsKey(gap)){
8+
int j = hashMap.get(gap);
9+
return new int[]{i,j};
10+
}
11+
hashMap.put(nums[i], i);
12+
}
13+
return null;
14+
}
15+
}

0 commit comments

Comments
 (0)