思路:利用数组对象存储数据结构,对象中有两个成员一个是输入的数组中的数据num,另外一个是num对应的1的个数,数据结构建构好后,按题意对数组对象进行排序,排序规则是:先用1的个数进行从大到小排序,当1的个数相同时,利用num排序,最后输出排序后的结果中的num即可。
代码:
import java.util.Arrays;
public class Solution {
class Data implements Comparable<Data> {
int num;
int one;
@Override
public int compareTo(Data o) {
// TODO Auto-generated method stub
if (this.one > o.one) {
return -1;
} else if (this.one < o.one) {
return 1;
} else {
return this.num > o.num ? -1 : (this.num < o.num ? 1 : 0);
}
}
}
public int numOf1(int n) {
int count = 0;
while (n != 0) {
n &= n - 1;
count++;
}
return count;
}
public int[] fun(int num, int element, int[] streamNum) {
if (streamNum == null || streamNum.length == 0 || num == 0 || element == 0)
return new int[1];
Data[] datas = new Data[num];
for (int i = 0; i < num; i++) {
Data d = new Data();
d.num = streamNum[i];
d.one = numOf1(streamNum[i]);
datas[i] = d;
}
Arrays.sort(datas);
int[] result = new int[element];
for (int i = 0; i < element; i++) {
result[i] = datas[i].num;
}
return result;
}
public static void main(String[] args) {
Solution solution = new Solution();
int[] result = solution.fun(10, 3, new int[] { 15, 15, 15, 15, 15, 2, 3, 5, 14, 1 });
System.out.println(Arrays.toString(result));
}
}