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"))