美文网首页
LeetCode_1356. Sort Integers by

LeetCode_1356. Sort Integers by

作者: 钱晓缺 | 来源:发表于2020-07-10 18:11 被阅读0次

Given an integer array arr. You have to sort the integers in the array in ascending order by the number of 1'sin 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.

简单来说就是把列表里面的数字改成二进制,看谁的1多,1越多排名越靠后,一样多的,按照大小排列。

我首先使用冒泡算法算了一波:

arr.sort()

        for j in range(len(arr)-1):

            for i in range(len(arr)-1):

                if bin(arr[i]).count("1")>bin(arr[i+1]).count("1"):

                    b=arr[i]

                    arr[i]=arr[i+1]

                    arr[i+1]=b

                    j+=1

        return arr

运行时间2200Ms,时间复杂度n2。

这里有个简单的,一句话搞定

        return sorted(sorted(arr),key=lambda x:bin(x).count("1"))

相关文章

网友评论

      本文标题:LeetCode_1356. Sort Integers by

      本文链接:https://www.haomeiwen.com/subject/zknmcktx.html