Skip to content

Commit df31f67

Browse files
authored
Create sort-integers-by-the-number-of-1-bits.py
1 parent 73989b4 commit df31f67

File tree

1 file changed

+18
-0
lines changed

1 file changed

+18
-0
lines changed
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
# Time: O(nlogn)
2+
# Space: O(1)
3+
4+
class Solution(object):
5+
def sortByBits(self, arr):
6+
"""
7+
:type arr: List[int]
8+
:rtype: List[int]
9+
"""
10+
def popcount(n): # Time: O(logn) ~= O(1) if n is a 32-bit number
11+
result = 0
12+
while n:
13+
n &= n - 1
14+
result += 1
15+
return result
16+
17+
arr.sort(key=lambda x: (popcount(x), x))
18+
return arr

0 commit comments

Comments
 (0)