1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| class Solution { public int[] sortByBits(int[] arr) { Integer[] nums = new Integer[arr.length]; for (int i = 0; i < arr.length; i++) { nums[i] = arr[i]; } Arrays.sort(nums, (o1, o2) -> { int diff = Integer.compare(Integer.bitCount(o1), Integer.bitCount(o2)); if (diff != 0) { return diff; } return Integer.compare(o1, o2); });
for (int i = 0; i < nums.length; i++) { arr[i] = nums[i]; } return arr; } }
|
References
1356. Sort Integers by The Number of 1 Bits