力扣1356.根据数字二进制下1的数目排序

我们先来看一下题目力扣1356.根据数字二进制下1的数目排序_第1张图片
要求把数组中的数全都改编成二进制,而且输出后每个1数相同的还要重新排序。
要求把同一样1的数量分为一类,肯定不能直接暴力用很多列表,可以用字典,字典的key就是1的数量,代码如下

class Solution:
    def sortByBits(self, arr: List[int]) -> List[int]:

        y = {
     }
        for i in arr:
            z = list(bin(i))
            c = z.count('1')
            if c not in y:
                y[c] = [i]
            elif c in y:
                y[c].append(i)
        key = sorted(y.keys())
        w = []
        for a in key:
            w += sorted(y[a])
        return w

把二进制改为列表后,它就会分成一个一个的:

x = '123456'
print(list(x))
['1', '2', '3', '4', '5', '6']

你可能感兴趣的:(python,力扣,列表,python)