File tree Expand file tree Collapse file tree 5 files changed +91
-0
lines changed Expand file tree Collapse file tree 5 files changed +91
-0
lines changed Original file line number Diff line number Diff line change 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+
Original file line number Diff line number Diff line change 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+ }
Original file line number Diff line number Diff line change 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+ }
Original file line number Diff line number Diff line change 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+ }
Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments