根据设置位数对数组进行排序

时间:2021-03-31 16:51:36

标签: c++

示例:

输入:arr = [0,1,2,3,4,5,6,7,8]
输出:[0,1,2,4,8,3,5,6,7]

说明:[0] 是唯一一个 0 位的整数。
[1,2,4,8] 都有 1 位。
[3,5,6] 有 2 位。
[7] 有 3 位。
按位排序的数组为[0,1,2,4,8,3,5,6,7]

我尝试在 C++ 中使用自定义排序,但我不明白我哪里出错了!

这是我的代码!

class Solution {
public:
    static int setbits(int temp) {
        int c, n = temp;

        while(n > 0) {
            if(n & 1) c++;

            n = n >> 1;
        }

        return c;
    }

    static bool myfun(int a, int b) {
        int c1 = setbits(a);

        int c2 = setbits(b);

        if(c1 == c2 || c1 < c2) return a < b;

        return a > b;
    }

    vector<int> sortByBits(vector<int>& arr) {
        sort(arr.begin(), arr.end(), myfun);

        return arr;
    }
};

2 个答案:

答案 0 :(得分:2)

您忘记在 c 函数中初始化 setbits

int c = 0;

而且,比较器的逻辑有问题。我得到正确的结果

if (c1 == c2) return a < b;
return c1 < c2;

请注意,通过首先计算所有数字的权重并将它们保存在数组中,代码可能会更高效。

答案 1 :(得分:0)

替换

   if(c1 == c2 || c1 < c2) return a < b;

    return a > b;

 return (c1 <= c2 );
相关问题