Java-LeetCode1356. 根据数字二进制下 1 的数目排序-Comparator
- 算法
- Java-Integer, Comparator
public int[] sortByBits(int[] arr) { Integer[] integers = new Integer[arr.length]; for (int i = 0; i < arr.length; i++) { integers[i] = arr[i]; } // Arrays.sort(integers, (o1, o2) -> Integer.bitCount(o1) == Integer.bitCount(o2) ? o1 - o2 : Integer.bitCount(o1) - Integer.bitCount(o2)); Arrays.sort(integers, Comparator.comparing(x -> Integer.bitCount(x) * 10000 + x)); for (int i = 0; i < arr.length; i++) { arr[i] = integers[i]; } return arr; }
LeetCode题解 文章被收录于专栏
测试