leetcode刷题:1356. 根据数字二进制下 1 的数目排序

in hive-180932 •  9 months ago 

image.png

这题是简单题,我的思路很简单:
1.首先把数字转换成二进制
2.用count函数计算1出现的次数
3.建立一个以出现次数为KEY的list,把数组分类
4.使用sorted排序,输出结果

代码如下:

class Solution:
    def sortByBits(self,arr):
        d = dict()
        for i in arr:
            b = bin(i)
            number = b.count('1')
            if number not in d:
                d[number] = list()
            d[number].append(i)
        keys = sorted(d.keys())
        lists = list()
        for k in keys:
            lists += sorted(d[k])
        return lists

image.png

Authors get paid when people like you upvote their post.
If you enjoyed what you read here, create your account today and start earning FREE STEEM!
Sort Order:  
  ·  9 months ago 

拍拍