LeetCode知识点总结 - 1356

LeetCode 1356. Sort Integers by The Number of 1 Bits

考点难度
SortingEasy
题目

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;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值