알고리즘 스터디

[Leetcode/파이썬] 228.Summary Ranges

난쟁이 개발자 2025. 8. 13. 20:25
반응형

Summary Ranges

Difficulty: Easy


You are given a sorted unique integer array nums.

A range [a,b] is the set of all integers from a to b (inclusive).

Return the smallest sorted list of ranges that cover all the numbers in the array exactly. That is, each element of nums is covered by exactly one of the ranges, and there is no integer x such that x is in one of the ranges but not in nums.

Each range [a,b] in the list should be output as:

  • "a->b" if a != b
  • "a" if a == b

 

Example 1:

Input: nums = [0,1,2,4,5,7]
Output: ["0->2","4->5","7"]
Explanation: The ranges are:
[0,2] --> "0->2"
[4,5] --> "4->5"
[7,7] --> "7"

Example 2:

Input: nums = [0,2,3,4,6,8,9]
Output: ["0","2->4","6","8->9"]
Explanation: The ranges are:
[0,0] --> "0"
[2,4] --> "2->4"
[6,6] --> "6"
[8,9] --> "8->9"

 

Constraints:

  • 0 <= nums.length <= 20
  • -231 <= nums[i] <= 231 - 1
  • All the values of nums are unique.
  • nums is sorted in ascending order.

 

class Solution:
    def summaryRanges(self, nums: List[int]) -> List[str]:
        if nums == [] :
            return []
        
        if len(nums) == 1 :
            return [f"{nums[0]}"]

        res = []
        tmp = [nums[0], nums[0]]
        i = nums[0]

        for num in nums[1:] :
            i += 1
            if num == i :
                tmp[1] = i
            else :
                if tmp[0] != tmp[1] :
                    res.append(f"{tmp[0]}->{tmp[1]}")
                else :
                    res.append(f"{tmp[0]}")

                tmp = [num, num]
                i = num
        
        if tmp[0] != tmp[1] :
            res.append(f"{tmp[0]}->{tmp[1]}")
        else :
            res.append(f"{tmp[0]}")

        return res

예외 사항인 nums.length 가 0, 1 일때를 가볍게 가지치기를 하고, 구현을 하면 쉽게 해결할 수 있는 문제였다. 

처음 범위를 nums[0], nums[0]으로 설정하고 nums를 돌면서 i+1 = num 인지를 체크한다. 만약 아니라면 res 에 정답 포맷에 맞게 추가하고 num으로 갱신을 한다. 그리고 마지막에 한 번 더 체크하고 추가하면 정답처리가 된다. 마지막에 한 번 더 체크하는 이유는 nums[-1]의 경우는 res에 추가가 되지 않기 때문에 마지막에 한 번 더 체크하여 res에 추가하는 것이다. 

반응형