Skip to content

Commit

Permalink
Solve week 4 problems
Browse files Browse the repository at this point in the history
  • Loading branch information
bky373 committed Jun 3, 2024
1 parent 3e99718 commit c6ffd4f
Show file tree
Hide file tree
Showing 5 changed files with 91 additions and 0 deletions.
23 changes: 23 additions & 0 deletions counting-bits/bky373.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
/**
* https://leetcode.com/problems/counting-bits/
*
* time: O(n * log n)
* space: O(1)
*/
class Solution {

public int[] countBits(int n) {
int[] ans = new int[n + 1];
for (int i = 0; i <= n; i++) {
int x = i;
int cnt = 0;
while (x != 0) {
cnt++;
x &= (x - 1);
}
ans[i] = cnt;
}
return ans;
}
}

19 changes: 19 additions & 0 deletions group-anagrams/bky373.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
/**
* https://leetcode.com/problems/group-anagrams/
*
* time: O(n * m log m)
* space: O(nm)
*/
class Solution {

public List<List<String>> groupAnagrams(String[] strs) {
Map<String, List<String>> groups = new HashMap();
for (String str : strs) {
char[] arr = str.toCharArray();
Arrays.sort(arr);
groups.computeIfAbsent(new String(arr), k -> new ArrayList<>())
.add(str);
}
return new ArrayList(groups.values());
}
}
15 changes: 15 additions & 0 deletions missing-number/bky373.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
/**
* https://leetcode.com/problems/missing-number/
*
* time: O(n)
* space: O(1)
*/
class Solution {
public int missingNumber(int[] nums) {
int sum = nums.length * (nums.length+1) / 2;
for (int num : nums) {
sum -= num;
}
return sum;
}
}
17 changes: 17 additions & 0 deletions number-of-1-bits/bky373.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
/**
* https://leetcode.com/problems/number-of-1-bits/
*
* time: O(log n)
* space: O(1)
*/
class Solution {

public int hammingWeight(int n) {
int cnt = 0;
while (n != 0) {
cnt++;
n &= (n - 1);
}
return cnt;
}
}
17 changes: 17 additions & 0 deletions reverse-bits/bky373.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
/**
* https://leetcode.com/problems/reverse-bits/
*
* time: O(1)
* space: O(1)
*/
public class Solution {

public int reverseBits(int n) {
int ans = 0;
for (int i = 0; i < 32; i++) {
ans = ans << 1 | n & 1;
n >>= 1;
}
return ans;
}
}

0 comments on commit c6ffd4f

Please sign in to comment.