题目地址:
https://leetcode.com/problems/sort-integers-by-the-number-of-1-bits/
给定一个长 n n n数组 A A A,要求将其按照二进制表示里含 1 1 1的个数进行从小到大排序,如果有并列的则按原数值从小到大排序。
代码如下:
import java.util.Arrays;
public class Solution {
public int[] sortByBits(int[] A) {
int[][] tmp = new int[A.length][];
for (int i = 0; i < A.length; i++) {
tmp[i] = new int[]{A[i], cnt(A[i])};
}
Arrays.sort(tmp, (x, y) -> x[1] != y[1] ? Integer.compare(x[1], y[1]) : Integer.compare(x[0], y[0]));
int[] res = new int[A.length];
for (int i = 0; i < A.length; i++) {
res[i] = tmp[i][0];
}
return res;
}
private int cnt(int x) {
int res = 0;
while (x > 0) {
x -= x & -x;
res++;
}
return res;
}
}
时间复杂度 O ( n log n ) O(n\log n) O(nlogn),空间 O ( n ) O(n) O(n)。