LeetCode 1356. Sort Integers by The Number of 1 Bits (根据数字二进制下 1 的数目排序)

题目标签:Sort

  要利用到 Integer.bitCount(i) * 10000 + i 来排序。

       For instance [0,1,2,3,5,7], becomes something like this [0, 10001, 10002, 20003, 20005, 30007].

  具体看code。

 

 

Java Solution: 

Runtime:  23 ms, faster than 18.81 % 

Memory Usage: 47.4 MB, less than 5.04 %

完成日期:9/15/2020

关键点:Integer.bitCount(i) * 10000 + i

class Solution {
    public int[] sortByBits(int[] arr) {
        Integer[] a = new Integer[arr.length];
        
        for(int i = 0; i < a.length; i++) {
            a[i] = arr[i];
        }
        
        Arrays.sort(a, Comparator.comparing(i -> Integer.bitCount(i) * 10000 + i));
        
        for(int i = 0; i < a.length; i++) {
            arr[i] = a[i];
        }
        
        return arr;
    }
}

参考资料:https://leetcode.com/problems/sort-integers-by-the-number-of-1-bits/discuss/516985/JavaPython-3-1-liners.

LeetCode 题目列表 - LeetCode Questions List

题目来源:https://leetcode.com/

posted @ 2020-09-16 09:47  Jimmy_Cheng  阅读(166)  评论(0编辑  收藏  举报