【Leetcode】1356. Sort Integers by The Number of 1 Bits

该博客介绍了如何使用Java解决LeetCode上的一个问题,即根据整数的二进制表示中1的个数进行排序。代码中展示了如何创建一个二维数组存储原数组和对应的1位数计数,然后使用Arrays.sort进行排序,最后返回原始数值数组。时间复杂度为O(nlogn),空间复杂度为O(n)。
摘要由CSDN通过智能技术生成

题目地址:

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)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值