Problem Solving/LeetCode
2023.10.31 Today's Challenge
fabichoi
2023. 10. 31. 23:45
https://leetcode.com/problems/sort-integers-by-the-number-of-1-bits/
Sort Integers by The Number of 1 Bits - LeetCode
Can you solve this real interview question? 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 integ
leetcode.com
오랫만에 직접 품.
좀 더 간단한 방법이 있을지도..
class Solution:
def sortByBits(self, arr: List[int]) -> List[int]:
d = {}
res = []
for v in arr:
k = bin(v).count('1')
if not d.get(k):
d[k] = [v]
continue
d[k].append(v)
d = sorted(d.items())
for dd in d:
res.extend(sorted(dd[1]))
return res
반응형