zoukankan      html  css  js  c++  java
  • [leetCode]1356. 根据数字二进制下 1 的数目排序

    题目

    链接: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 <= arr.length <= 500
    0 <= arr[i] <= 10^4
    

    解法

    使用系统自带的排序函数修改一下排序规则。
    计算每个数字对应的二进制的1的个数可以通过十进制转二进制进行统计,也可以通过递归进行预处理

    class Solution {
        public int[] sortByBits(int[] arr) {
            List<Integer> list = new ArrayList<>();
            // 将数组中的数字添加进列表
            for (int x : arr) {
                list.add(x);
            }
            // bit[i] 表示数字i在二进制下1的个数
            int[] bit = new int[10001];
            // 预处理数组bit
            for (int i = 1; i < bit.length; i++) {
                bit[i] = bit[i >> 1] + (i & 1);
            }
            Collections.sort(list, new Comparator<Integer>() {
                public int compare(Integer o1, Integer o2) {
                    if (bit[o1] == bit[o2]) {
                        return o1 - o2;
                    } else {
                        return bit[o1] - bit[o2];
                    }
                }
            });
            int[] ans = new int[list.size()];
            for (int i = 0; i < ans.length; i++) {
                ans[i] = list.get(i);
            }
            return ans;
        }
    }
    
  • 相关阅读:
    HTML5 Canvas 颜色填充学习
    PHP中使用函数array_merge()合并数组
    div border-radius
    php中数组可以不写下标
    ab apache Benchmarking中链接的写法 记得加上/
    div border-radius画圆
    Why should i use url.openStream instead of of url.getContent?
    Using Java SecurityManager to grant/deny access to system functions
    In Java, what is the default location for newly created files?
    三种纯CSS实现三角形的方法
  • 原文地址:https://www.cnblogs.com/PythonFCG/p/13935003.html
Copyright © 2011-2022 走看看