LeetCode 1356. Sort Integers by The Number of 1 Bits
考点 | 难度 |
---|---|
Sorting | Easy |
题目
You are given an integer array arr
. Sort the integers in the array in ascending order by the number of 1’s in their binary representation and in case of two or more integers have the same number of 1’s you have to sort them in ascending order.
Return the array after sorting it.
思路
先把数字和二进制中1出现的次数存在int[][]
里。设计一个comparator比较两个数(和二进制)的顺序关系。用comparator给int[][]
排序,最后把数值按顺序存到int[]
中返回。
答案
class Solution {
class myCmp implements Comparator<int[]> {
public int compare(int[] a, int[] b) {
if(a[1] != b[1]) {
return a[1]-b[1];
} else {
return a[0]-b[0];
}
}
}
public int[] sortByBits(int[] arr) {
int[][] count = new int[arr.length][2];
for(int i = 0; i < arr.length; i++){
count[i][0] = arr[i];
count[i][1] = Integer.bitCount(arr[i]);
}
Arrays.sort(count, new myCmp());
for(int i = 0; i < arr.length; i++){
arr[i] = count[i][0];
}
return arr;
}
}