题目
给你一个整数数组 arr 。请你将数组中的元素按照其二进制表示中数字 1 的数目升序排序。
如果存在多个数字二进制中 1 的数目相同,则必须将它们按照数值大小升序排列。
请你返回排序后的数组。
思路
这道题其实是考察如何计算一个数的二进制中1的数量。
方法一:
老老实实挨个计算1的数量,循环n的二进制位数
int bitCount(int n){
int count = 0;
while(n > 0){
if( (n & 1) == 1) count++;//n & 1表示n和1按位与,全1出1,有0出0,(n & 1) == 1表示当前位为1
n >>= 1;
}
}
方法二:这个方法,只循环n的二进制中1的个数次,比方法一更高效
int bitCount(int n){
int count = 0;
while(n){
n &= (n - 1);//清除最低位的1
count++;
}
return count;
}
以计算12的二进制1的数量为例,如图所示:
这里使用方法二:
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) {
//boxed()的作用就是将基本(原始)类型的stream转成了包装(boxed)类型的Stream
return Arrays.stream(arr).boxed()
.sorted(new Comparator<Integer>(){
@Override
public int compare(Integer o1, Integer o2) {
int cnt1 = cntInt(o1);
int cnt2 = cntInt(o2);
return (cnt1 == cnt2) ? Integer.compare(o1, o2) : Integer.compare(cnt1, cnt2);
}
})
.mapToInt(Integer::intValue)
.toArray();
}