소프트웨어에 대한 모든 것

LeetCode 풀기 - 1742. Maximum Number of Balls in a Box 본문

알고리즘/LeetCode

LeetCode 풀기 - 1742. Maximum Number of Balls in a Box

앤테바 2021. 12. 14. 06:53
반응형

1742. Maximum Number of Balls in a Box

https://leetcode.com/problems/maximum-number-of-balls-in-a-box/

 

Maximum Number of Balls in a Box - 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 countBalls(self, lowLimit: int, highLimit: int) -> int:
        d = defaultdict(int)
        
        def get_box_num(n):
            str_n = str(n)
            return sum([int(v) for v in str_n])        
        
        for n in range(lowLimit, highLimit+1):
            box_number = get_box_num(n)
            d[box_number] += 1            
            
        return max(d.values())

솔루션2)

솔루션1의 속도를 개선 하였습니다.

기존의 get_box_num() 함수는 숫자를 문자열로 변환 후 반복문을 돌면서 숫자로 변환해서 sum을 취했다면,

나머지 연산과 나누기 연산을 통해서 get_box_num()를 구하도록 변경하였습니다.

class Solution:
    def countBalls(self, lowLimit: int, highLimit: int) -> int:
        d = defaultdict(int)
        
        def get_box_num(n):
            sum1 = 0
            while n:
                sum1 += n % 10
                n //= 10
            return sum1
        
        for n in range(lowLimit, highLimit+1):
            box_number = get_box_num(n)
            d[box_number] += 1            
            
        return max(d.values())

 

반응형
Comments