1356 根据数字二进制下1的数目排序

直接除基取余法暴力

class Solution {
    int m[10005];
public:
    vector<int> sortByBits(vector<int>& arr) {
        memset(m, 0, sizeof(m));
        for(int i : arr)
        {
            int x = i; // 不改变原数组
            if(!m[x]) // 未计算过的数字
            {
                while(x) // 除基取余法
                {
                    if(x % 2) ++m[i];
                    x /= 2;
                }
            }
        }
        sort(arr.begin(), arr.end(),
            [&](const int a, const int b){return m[a] == m[b] ? a < b : m[a] < m[b];});
        return arr;
    }
};

用时16ms

分析答案中采用的位运算:

    int get(int x){
        int res=0;
        while (x) res+=x&1,x>>=1;
        return res;
    }

x & 1即判断x对应的二进制末位是否为1,res+过后,x >>= 1整体右移一位,最后一位被移掉,达到统计对应二进制中1的个数的效果,更快

修改后用时12ms

#include <bits/stdc++.h>
using namespace std;

class Solution {
    int m[10005];
public:
    vector<int> sortByBits(vector<int>& arr) {
        memset(m, 0, sizeof(m));
        for(int i : arr)
        {
            int x = i; // 不改变原数组
            if(!m[x]) // 未计算过的数字
            {
                while(x) // 除基取余法
                {
                    if(x & 1) ++m[i];
                    x >>= 1;
                }
            }
        }
        sort(arr.begin(), arr.end(),
            [&](const int a, const int b){return m[a] == m[b] ? a < b : m[a] < m[b];});
        return arr;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值