链接 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.
草不知不觉一周没写题解了
12345678910111213141516171819202122
from typing import List, Dictfrom collections import Counter, defaultdict, OrderedDictclass 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