leetcode1356

 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

Algorithm thinking: bit computing.

Title Prerequisite 0 <= arr [i] <= 10 ^ 4, thus countBitOnes (inside), 32 cycles can not only need to cycle 14 times, 2 ^ 14 = 16384> 10000.

Guess you like

Origin www.cnblogs.com/asenyang/p/12348438.html