LeetCode——1356. Sort according to the number of 1s in digital binary

Topic description:

Gives you an integer array arr. Please sort the elements in the array in ascending order of the number of 1 in their binary representation. If there are multiple digital binary numbers with the same number of 1s, they must be arranged in ascending order of numerical value. Please return the sorted array.

prompt:

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

Example 1:
Input: arr = [0,1,2,3,4,5,6,7,8]
Output: [0,1,2,4,8,3,5,6,7]
Explanation: [ 0] is the only number with 0 ones.
[1,2,4,8] has 1 1 each.
[3,5,6] has 2 ones.
[7] There are 3 1s.
The result array obtained by sorting by the number of 1 is [0,1,2,4,8,3,5,6,7]

Example 2:
Input: arr = [1024,512,256,128,64,32,16,8,4,2,1]
Output: [1,2,4,8,16,32,64,128,256,512,1024]
Explanation: All in the array There is only one 1 in integer binary, so you need to sort them according to the numerical value.

Example 3:
Input: arr = [10000,10000]
Output: [10000,10000]

Example 4:
Input: arr = [2,3,5,7,11,13,17,19]
Output: [2,3,5,17,7,11,13,19]

Example 5:
Input: arr = [10,100,1000,10000]
Output: [10,100,10000,1000]

code show as below:

class Solution {
    
    
    public int[] sortByBits(int[] arr) {
    
    
        int[] bit = new int[10001];
        List<Integer> list = new ArrayList<Integer>();
        for (int x : arr) {
    
    
            list.add(x);
            bit[x] = get(x);
        }
        Collections.sort(list, new Comparator<Integer>() {
    
    
            public int compare(Integer x, Integer y) {
    
    
                if (bit[x] != bit[y]) {
    
    
                    return bit[x] - bit[y];
                } else {
    
    
                    return x - y;
                }
            }
        });
        for (int i = 0; i < arr.length; ++i) {
    
    
            arr[i] = list.get(i);
        }
        return arr;
    }

    public int get(int x) {
    
    
        int count = 0;
        String s = Integer.toBinaryString(x);
        for (int i = 0; i < s.length(); i++) {
    
    
            if (s.charAt(i) == '1') {
    
    
                count++;
            }
        }
        return count;
    }
}

Results of the:
Insert picture description here

Guess you like

Origin blog.csdn.net/FYPPPP/article/details/114695621