【leetcode】1356. 根据数字二进制下 1 的数目排序(sort-integers-by-the-number-of-1-bits)(模拟)[简单]

215 篇文章 0 订阅
66 篇文章 0 订阅

链接

https://leetcode-cn.com/problems/sort-integers-by-the-number-of-1-bits/

耗时

解题:15 min
题解:6 min

题意

给你一个整数数组 arr 。请你将数组中的元素按照其二进制表示中数字 1 的数目升序排序。

如果存在多个数字二进制中 1 的数目相同,则必须将它们按照数值大小升序排列。

请你返回排序后的数组。

思路

结构体中记录整数值和整数二进制中 1 的数目,然后结构体排序。

时间复杂度: O ( n l o g n ) O(nlogn) O(nlogn)

AC代码

class Solution {
private:
    struct node {
        int val, cnt;
        bool operator < (const node &d) const {
            return cnt == d.cnt ? (val <= d.val) : (cnt < d.cnt);//从小到大
        }
    };
public:
    vector<int> sortByBits(vector<int>& arr) {
        vector<node> res;
        for(auto x : arr) {
            int x_backup = x;
            int cntx = 0;
            while(x) {
                if(x&1) cntx++;
                x >>= 1;
            }
            res.push_back((node){x_backup, cntx});
        }
        sort(res.begin(), res.end());
        vector<int> ans;
        for(auto x : res) {
            ans.push_back(x.val);
        }
        return ans;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值