Leetcode 1356. Sort Integers by The Number of 1 Bits

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

1. Description

Sort Integers by The Number of 1 Bits

2. Solution

**解析:**由于最大数字不超过10000,因此1的位数不超过14位,注意+=的运算优先级要低于&,而+的运算优先级要高于&。Version 1用右移运算获得1的个数,Version 2用的bin函数,Version 3通过python自带的排序函数进行排序。Version 4使用字典保存结果。

  • Version 1
class Solution:
    def sortByBits(self, arr: List[int]) -> List[int]:
        result = []
        stat = [[] for i in range(15)]
        for num in arr:
            bits = self.bitCount(num)
            stat[bits].append(num)
        for temp in stat:
            temp.sort()
            result += temp
        return result


    def bitCount(self, num):
        count = 0
        while num:
            count += (num & 1)
            num = num >> 1
        return count
  • Version 2
class Solution:
    def sortByBits(self, arr: List[int]) -> List[int]:
        arr.sort()
        result = []
        stat = [[] for i in range(15)]
        for num in arr:
            bits = bin(num).count('1')
            stat[bits].append(num)
        for temp in stat:
            result += temp
        return result
  • Version 3
class Solution:
    def sortByBits(self, arr: List[int]) -> List[int]:
        return sorted(arr, key=lambda x: [bin(x).count('1'), x])
  • Version 4
class Solution:
    def sortByBits(self, arr: List[int]) -> List[int]:
        arr.sort()
        result = []
        stat = collections.defaultdict(list)
        for num in arr:
            stat[bin(num).count('1')].append(num)
        for index in sorted(list(stat.keys())):
            result += stat[index]
        return result

Reference

  1. https://leetcode.com/problems/sort-integers-by-the-number-of-1-bits/
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值