标签:solution == 思路 img font inf sof def family
思路:
本题有两个排序条件:
二进制中‘1’的个数、十进制数值大小,因此用sort()和sorted()都可实现。
代码如下。
1 class Solution(object): 2 def sortByBits(self, arr): 3 """ 4 :type arr: List[int] 5 :rtype: List[int] 6 """ 7 arr.sort(key=lambda num: (bin(num)[2:].count(‘1‘), num), reverse=False) 8 return arr 9 10 def sortByBits2(self, arr): 11 """ 12 :type arr: List[int] 13 :rtype: List[int] 14 """ 15 return sorted(arr, key=lambda num: (bin(num)[2:].count(‘1‘), num), reverse=False) 16 17 18 if __name__ == ‘__main__‘: 19 solution = Solution() 20 print(solution.sortByBits(arr=[0, 1, 7, 8, 2, 3, 4, 5, 6]))
标签:solution == 思路 img font inf sof def family
原文地址:https://www.cnblogs.com/panweiwei/p/12712756.html