根据数字二进制下 1 的数目排序


错误代码

Arrays.sort(arr,(l,r)->l-r)后面自定义必须是类

正确代码

class Solution {

    public int[] sortByBits(int[] arr) {
        int n = arr.length;
        int[] res = new int[n];
        Node[] nodes = new Node[n];
        for(int i=0;i<n;i++){
            nodes[i] = new Node(arr[i],oneNum(arr[i]));
        }
        //对于后面用(l,r)->l-r之类的,l和r必须是封装类型否则会报错
        Arrays.sort(nodes,(l,r)->{
            if(l.bitCnt != r.bitCnt) return l.bitCnt - r.bitCnt;
            return l.val - r.val;
        });
        for(int i=0;i<n;i++){
            res[i] = nodes[i].val;
        }
        return res;


   
    }
    public int oneNum(int num){
        int cnt = 0;
        while(num != 0){
            cnt++;
            num = num & (num-1);//消去最右边的1
        }
        return cnt;

    }
}
class Node{
    int val;
    int bitCnt;
    Node(int val,int bitCnt){
        this.val = val;
        this.bitCnt = bitCnt;
    }
}

posted @ 2020-11-06 21:45  浅滩浅  阅读(199)  评论(0编辑  收藏  举报