HashMap is sorted in ascending order by Value, and the same value is sorted in ascending order by Key

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.

Note: The same elements are not included in arr.

class Solution {
    
    
    public int[] sortByBits(int[] arr) {
    
    
        int n = arr.length;
        int[] nums = new int[n];
        HashMap<Integer, Integer> map = new HashMap<>();
        for (int j : arr) {
    
    
            map.put(j, By(j));
        }
        List<Map.Entry<Integer, Integer>> list = new LinkedList<>(map.entrySet());
        list.sort(new Comparator<Map.Entry<Integer, Integer>>() {
    
    
            @Override
            public int compare(Map.Entry<Integer, Integer> o1, Map.Entry<Integer, Integer> o2) {
    
    
                int res = o1.getValue() - o2.getValue();
                if (res == 0) {
    
    
                    res = o1.getKey() - o2.getKey();
                }
                return res;
            }
        });
        int k = 0;
        Map<Integer, Integer> result = new HashMap<>();
        for (Map.Entry<Integer, Integer> entry : list) {
    
    
            nums[k] = entry.getKey();
            k++;
        }
        return nums;
    }

    public int By(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;
    }
}

Guess you like

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