Loading

【每日一题】LeetCode 1356. 根据数字二进制下 1 的数目排序

Link

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

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

请你返回排序后的数组。

  • 1 <= arr.length <= 500
  • 0 <= arr[i] <= 10^4

使用 std::sort() 并自定义比较器可以解决此题。

自定义比较器即提供元素之间的小于号关系(不是小于等于号!)。

提供小于等于可能导致运行时错误(原因)。

class Solution {
public:
    vector<int> sortByBits(vector<int>& arr) {
        std::sort(arr.begin(), arr.end(), [](int x, int y) {
            return __builtin_popcount(x) == __builtin_popcount(y) ? x < y : __builtin_popcount(x) < __builtin_popcount(y);
        });
        return arr;
    }
};
posted @ 2026-02-25 22:03  escap1st  阅读(12)  评论(0)    收藏  举报