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

题目描述: 给你一个整数数组 \(arr\)。请你将数组中的元素按照其二进制表示中数字 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]

输入: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 ,所以你需要按照数值大小将它们排序。

class Solution {
public:
    int get(int x){
        int res = 0;
        while (x) {
            res += (x % 2);
            x /= 2;
        }
        return res;
    }
    vector<int> sortByBits(vector<int>& arr) {
        vector<int> bit(10001, 0);
        for (auto x: arr) {
            bit[x] = get(x);
        }
        sort(arr.begin(),arr.end(),[&](int x,int y){
            if (bit[x] < bit[y]) {
                return true;
            }
            if (bit[x] > bit[y]) {
                return false;
            }
            return x < y;
        });
        return arr;
    }
};
class Solution {
public:
    vector<int> sortByBits(vector<int>& arr) {
        vector<int> bit(10001, 0);
        for (int i = 1;i <= 10000; ++i) {
            bit[i] = bit[i>>1] + (i & 1);
        }
        sort(arr.begin(),arr.end(),[&](int x,int y){
            if (bit[x] < bit[y]) {
                return true;
            }
            if (bit[x] > bit[y]) {
                return false;
            }
            return x < y;
        });
        return arr;
    }
};
class Solution {
public:
    class myComparison{
    public:
        bool operator() (const pair<int, int>& pair_first, const pair<int, int>& pair_second){ // first表示数值的大小, second 表示数值中1的个数
            if( pair_first.second > pair_second.second ){
                return true;
            }else if ( pair_first.second < pair_second.second ){
                return false;
            }else {
                return pair_first.first > pair_second.first;
            }
        } 
    };
    vector<int> sortByBits(vector<int>& arr) {
        priority_queue<pair<int, int>, vector<pair<int,int>>, myComparison> pq;
        vector<int> temp (arr.begin(), arr.end());
        int n = temp.size();
        // unordered_map<int, int> map;
        vector<pair<int,int>> map;
        for(int i = 0; i < n; i++){
            int count = 0; 
            while(temp[i] > 0){
                count++;
                temp[i] = temp[i] & (temp[i] - 1);
            }
            map.push_back({arr[i], count});
        }
        for(auto it = map.begin(); it != map.end(); it++){
            cout<< " it->first = "<< it->first <<" i->second = " << it->second <<endl;
            pq.emplace(*it);
        }
        vector<int> res;
        while (!pq.empty()){
            res.push_back(pq.top().first);
            pq.pop();
        }
        return res;
    }
};
posted @ 2020-11-27 20:37  wsl-hitsz  阅读(92)  评论(0编辑  收藏  举报