Leetcode刷题笔记 1356.根据数字二进制下 1 的数目排序

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

时间:2020年11月6日
知识点:位运算、排序
题目链接:https://leetcode-cn.com/problems/sort-integers-by-the-number-of-1-bits/

题目
给你一个整数数组 arr 。请你将数组中的元素按照其二进制表示中数字 1 的数目升序排序。
如果存在多个数字二进制中 1 的数目相同,则必须将它们按照数值大小升序排列。
请你返回排序后的数组。

示例 1:

输入
arr = [0,1,2,3,4,5,6,7,8]
输出
[0,1,2,4,8,3,5,6,7]
解释
[0] 是唯一一个有 0 个 1 的数。
[1,2,4,8] 都有 1 个 1 。
[3,5,6] 有 2 个 1 。
[7] 有 3 个 1 。
按照 1 的个数排序得到的结果数组为 [0,1,2,4,8,3,5,6,7]

示例 2
输入
arr = [1024,512,256,128,64,32,16,8,4,2,1]
输出
[1,2,4,8,16,32,64,128,256,512,1024]
解释
数组中所有整数二进制下都只有 1 个 1 ,所以你需要按照数值大小将它们排序。

示例3
输入
arr = [10000,10000]
输出
[10000,10000]

示例 4:
输入
arr = [2,3,5,7,11,13,17,19]
输出
[2,3,5,17,7,11,13,19]

示例 5
输入
arr = [10,100,1000,10000]
输出
[10,100,10000,1000]

提示

  1. 1<= arr.length <= 500
  2. 0 <= arr[i] <= 104

解法

  1. 统计每个数字二进制下1的个数排序
  2. x &1 对x mod 2 取余数
  3. x >>= 1 x=x/2

代码

#include <stdio.h>
#include <iostream>
#include <vector>
using namespace std;
bool cmp(pair<int, int> a,pair<int, int> b){
    if(a.second == b.second)
        return a.first < b.first;
    return a.second < b.second;
}
class Solution {
public:
    vector<int> sortByBits(vector<int>& arr) {
        vector<pair<int, int>> dic;
        vector<int> ans;
        for(int i=0;i<arr.size();i++){
            int x = arr[i];
            int count = 0;
            while(x){
                count += x&1;
                x>>=1;
            }
            dic.push_back(pair<int, int>(arr[i], count));
        }
        sort(dic.begin(),dic.end(),cmp);
        for(int i=0;i<arr.size();i++){
            ans.push_back(dic[i].first);
        }
        return ans;
    }
};
int main()
{
    vector<int> arr{0,1,2,3,4,5,6,7,8};
    Solution s;
    vector<int> ans = s.sortByBits(arr);
    for(int x:ans){
        cout<<x<<endl;
    }
    return 0;
}

今天也是爱zz的一天哦!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值