Skip to content

Commit 410ad39

Browse files
authored
Merge pull request #113 from bky373/main
[bky373] Solve week 4 problems
2 parents c890b73 + c6ffd4f commit 410ad39

File tree

5 files changed

+91
-0
lines changed

5 files changed

+91
-0
lines changed

counting-bits/bky373.java

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
/**
2+
* https://leetcode.com/problems/counting-bits/
3+
*
4+
* time: O(n * log n)
5+
* space: O(1)
6+
*/
7+
class Solution {
8+
9+
public int[] countBits(int n) {
10+
int[] ans = new int[n + 1];
11+
for (int i = 0; i <= n; i++) {
12+
int x = i;
13+
int cnt = 0;
14+
while (x != 0) {
15+
cnt++;
16+
x &= (x - 1);
17+
}
18+
ans[i] = cnt;
19+
}
20+
return ans;
21+
}
22+
}
23+

group-anagrams/bky373.java

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
/**
2+
* https://leetcode.com/problems/group-anagrams/
3+
*
4+
* time: O(n * m log m)
5+
* space: O(nm)
6+
*/
7+
class Solution {
8+
9+
public List<List<String>> groupAnagrams(String[] strs) {
10+
Map<String, List<String>> groups = new HashMap();
11+
for (String str : strs) {
12+
char[] arr = str.toCharArray();
13+
Arrays.sort(arr);
14+
groups.computeIfAbsent(new String(arr), k -> new ArrayList<>())
15+
.add(str);
16+
}
17+
return new ArrayList(groups.values());
18+
}
19+
}

missing-number/bky373.java

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
/**
2+
* https://leetcode.com/problems/missing-number/
3+
*
4+
* time: O(n)
5+
* space: O(1)
6+
*/
7+
class Solution {
8+
public int missingNumber(int[] nums) {
9+
int sum = nums.length * (nums.length+1) / 2;
10+
for (int num : nums) {
11+
sum -= num;
12+
}
13+
return sum;
14+
}
15+
}

number-of-1-bits/bky373.java

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
/**
2+
* https://leetcode.com/problems/number-of-1-bits/
3+
*
4+
* time: O(log n)
5+
* space: O(1)
6+
*/
7+
class Solution {
8+
9+
public int hammingWeight(int n) {
10+
int cnt = 0;
11+
while (n != 0) {
12+
cnt++;
13+
n &= (n - 1);
14+
}
15+
return cnt;
16+
}
17+
}

reverse-bits/bky373.java

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
/**
2+
* https://leetcode.com/problems/reverse-bits/
3+
*
4+
* time: O(1)
5+
* space: O(1)
6+
*/
7+
public class Solution {
8+
9+
public int reverseBits(int n) {
10+
int ans = 0;
11+
for (int i = 0; i < 32; i++) {
12+
ans = ans << 1 | n & 1;
13+
n >>= 1;
14+
}
15+
return ans;
16+
}
17+
}

0 commit comments

Comments
 (0)