leetcode 1356. Sort Integers by The Number of 1 Bits

问题来自 leetcode 1356. Sort Integers by The Number of 1 Bits


用sort来做,sort的时候保留一些信息


class CustomComparator {
    public:
        bool operator()(const pair<int, int> &a, const 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) {
        int size = arr.size();
        vector<pair<int, int>> tool(size);
        for (int i = 0; i < size; ++i) {
            tool[i] = {arr[i], oneBits(arr[i])};
        }
        
        sort(tool.begin(), tool.end(), CustomComparator());
        
        vector<int> result(size);
        for (int i = 0; i < size; ++i)             
            result[i] = tool[i].first;                  
            return result;     
        }          

    int oneBits(int a) {         
        int ret = 0;         
        while(a != 0) {             
            ret += (a&0x1);             
            a >>= 1;
        }
        return ret;
    }
};

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.