标签:ntb code span turn 需要 rtb else port 算法思路
1 import collections 2 class Solution: 3 def countBitOnes(self,num): 4 count = 0 5 for i in range(14): 6 if num & 1 == 1: 7 count += 1 8 num >>= 1 9 return count 10 11 def sortByBits(self, arr: ‘List[int]‘) -> ‘List[int]‘: 12 dic = collections.OrderedDict() 13 for num in arr: 14 count = self.countBitOnes(num) 15 #print(count) 16 if count not in dic: 17 dic[count] = [num] 18 else: 19 dic[count].append(num) 20 result = [] 21 sort_dic = sorted(dic.items(),key=lambda d:d[0]) 22 # print(sort_dic) 23 for k,v in sort_dic: 24 result += sorted(v) 25 return result
算法思路:位运算。
题目前提条件0 <= arr[i] <= 10^4,因此在countBitOnes()内,可以不用循环32次,只需要循环14次即可,2^14=16384>10000。
标签:ntb code span turn 需要 rtb else port 算法思路
原文地址:https://www.cnblogs.com/asenyang/p/12348438.html