mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 00:43:04 +08:00
Update 1356.根据数字二进制下1的数目排序.md
增加Java实现
This commit is contained in:
@ -123,6 +123,32 @@ public:
|
||||
## Java
|
||||
|
||||
```java
|
||||
class Solution {
|
||||
private int cntInt(int val){
|
||||
int count = 0;
|
||||
while(val > 0) {
|
||||
val = val & (val - 1);
|
||||
count ++;
|
||||
}
|
||||
|
||||
return count;
|
||||
}
|
||||
|
||||
public int[] sortByBits(int[] arr) {
|
||||
return Arrays.stream(arr).boxed()
|
||||
.sorted(new Comparator<Integer>(){
|
||||
@Override
|
||||
public int compare(Integer o1, Integer o2) {
|
||||
// TODO Auto-generated method stub
|
||||
int cnt1 = cntInt(o1);
|
||||
int cnt2 = cntInt(o2);
|
||||
return (cnt1 == cnt2) ? Integer.compare(o1, o2) : Integer.compare(cnt1, cnt2);
|
||||
}
|
||||
})
|
||||
.mapToInt(Integer::intValue)
|
||||
.toArray();
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
|
Reference in New Issue
Block a user