给你一个整数数组 arr 。请你将数组中的元素按照其二进制表示中数字 1 的数目升序排序。
如果存在多个数字二进制中 1 的数目相同,则必须将它们按照数值大小升序排列。
请你返回排序后的数组。
解答:统计二进制1的个数可以分别获取每个二进制位数,然后再统计其1的个数,此方法效率比较低。这里介绍另外一种高效的方法,同样以 34520 为例,我们计算其 a &= (a-1)的结果:
第一次:计算前:1000 0110 1101 1000 计算后:1000 0110 1101 0000 第二次:计算前:1000 0110 1101 0000 计算后:1000 0110 1100 0000 第二次:计算前:1000 0110 1100 0000 计算后:1000 0110 1000 0000 我们发现,没计算一次二进制中就少了一个 1 因此可以用此方法求1的个数,即下面的count_one函数。
int count_one(int a){
int cnt = 0;
while(a) a = a&(a-1), cnt++;
return cnt;
}
bool cmp(int a, int b){
int numa = count_one(a), numb = count_one(b);
return numa != numb? numa<numb:a<b;
}
class Solution {
public:
vector<int> sortByBits(vector<int>& arr) {
sort(arr.begin(),arr.end(),cmp);
return arr;
}
};
放在类外就不用关键字static的事,放里面如下
class Solution {
private:
static int count_one(int a){
int cnt=0;
while(a!=0){
a= a & (a-1);
cnt++;
}
return cnt;
}
static bool cmp(int a,int b){
int numa = count_one(a);
int numb = count_one(b);
//数字a和数字b不相等,比较1的个数,相等,比较值的大小。
return numa!=numb? numa<numb : a<b;
}
public:
vector<int> sortByBits(vector<int>& arr) {
sort(arr.begin(),arr.end(),cmp);
return arr;
}
};
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/sort-integers-by-the-number-of-1-bits
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。