-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path1356.py
35 lines (25 loc) · 786 Bytes
/
1356.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# https://leetcode.com/problems/sort-integers-by-the-number-of-1-bits/description/
from functools import cmp_to_key
from typing import List
def comparator(item1, item2):
if item1[1] > item2[1]:
return 1
elif item1[1] < item2[1]:
return -1
else:
if item1[0] > item2[0]:
return 1
else:
return -1
class Solution:
def sortByBits(self, arr: List[int]) -> List[int]:
bin_count = []
for n in arr:
number_of_ones = 0
while n > 0:
n = n & (n - 1)
number_of_ones += 1
bin_count.append(number_of_ones)
result = list(zip(arr, bin_count))
result.sort(key=cmp_to_key(comparator))
return [n[0] for n in result]