Loading...

10-31 leetcode-1356

链接 1356. Sort Integers by The Number of 1 Bits

题目

You are given an integer array arr. Sort the integers in the array in ascending order by the number of 1’s in their binary representation and in case of two or more integers have the same number of 1’s you have to sort them in ascending order.

Return the array after sorting it.

题解

草不知不觉一周没写题解了

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
from typing import List, Dict
from collections import Counter, defaultdict, OrderedDict


class Solution:
def sortByBits(self, arr: list[int]) -> list[int]:
if not arr:
return []
arr.sort()
count_map: dict[int, List[int]] = {}
for item in arr:
binary_count = Counter(bin(item))
if "1" not in binary_count:
count_map.setdefault(0, []).append(item)
else:
count_map.setdefault(binary_count["1"], []).append(item)
result_map: OrderedDict = OrderedDict(
sorted(count_map.items(), key=lambda x: x[0])
)
result = []
[result.extend(x) for x in result_map.values()]
return result

Comment