소프트웨어에 대한 모든 것

LeetCode 풀기 - 1356. Sort Integers by The Number of 1 Bits 본문

알고리즘/LeetCode

LeetCode 풀기 - 1356. Sort Integers by The Number of 1 Bits

앤테바 2021. 12. 29. 20:18
반응형

1356. Sort Integers by The Number of 1 Bits

https://leetcode.com/problems/sort-integers-by-the-number-of-1-bits/

 

Sort Integers by The Number of 1 Bits - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

문제)

솔루션1)

class Solution:
    def sortByBits(self, arr: List[int]) -> List[int]:
        d = {}
        
        # 0 <= arr[i] <= 10000
        for i in range(15):
            d[i] = []

        for n in arr:
            count = bin(n).count('1')
            d[count].append(n)
         
        res = []
        for nums in d.values():
            if nums:
                nums.sort()
                res += nums
                
        return res

솔루션2)

class Solution:
    def sortByBits(self, arr: List[int]) -> List[int]:
        return sorted(arr, key=lambda x: [bin(x).count('1'), x])

 

반응형
Comments