LeetCode-1356-Sort-Integers-By-Number-Of-1-Bits
🧠 Summary of Thoughts
- Precompute bit counts using a HashMap
- Convert
int[]toInteger[], sinceArrays.sort()with a customComparatordoes NOT work on primitiveint[] - Sort using a custom Comparator
- Copy back to
int[]
Learned:
Custom sort:
Arrays.sort(nums, new Comparator<Integer>() { ... });Lambda Structure:
1
2
3
4
5
6
7
8
9
10(a, b) -> {
//...
}
// it is equvalent to:
public int compare(Integer a, Integer b) {
//...
}- Example:
tradition method:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15Arrays.sort(nums, new Comparator<Integer>() {
@Override
public int compare(Integer a, Integer b) {
int bitA = arrays.get(a);
int bitB = arrays.get(b);
if (bitA != bitB) {
return bitA - bitB;
}
return a - b;
}
});Lambda:
1
2
3
4
5
6
7
8
9
10Arrays.sort(nums, (a, b) -> {
int bitA = arrays.get(a);
int bitB = arrays.get(b);
if (bitA != bitB) {
return bitA - bitB;
}
return a - b;
});
- Example:
❗ Easily wrong point
- We need to copy each
arrelement into a temporary variable so as to protect the original values!!!
✅ Code(Java)
1.
1 | |
- optimal solution
1 | |
LeetCode-1356-Sort-Integers-By-Number-Of-1-Bits
https://powersixxx.github.io/leetcode-blog/2026/02/26/LeetCode-1356-Sort-Integers-By-Number-Of-1-Bits/