Skip to content

Latest commit

 

History

History
55 lines (42 loc) · 2.32 KB

File metadata and controls

55 lines (42 loc) · 2.32 KB

🍥 LeetCode 228. Summary Ranges

  • Date : 2021.08.22(일)
  • Time : 30분

Problem

  • You are given a sorted unique integer array nums.
  • 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
    

Constraints

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

Example

  • 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"
    



풀이

def summaryRanges(self, nums: List[int]) -> List[str]:
        answer = []
        start = 0
        end = 0

        while start < len(nums):
            while end + 1 < len(nums) and nums[end + 1] == nums[end] + 1:
                end += 1
            answer.append(f"{nums[start]}->{nums[end]}" if start != end else f"{nums[start]}")
            start = end + 1
            end = start

        return answer

: 조금 복잡했던 문제.. 숫자가 이어져 있으면 그 시작과 끝을 정해서 시작->끝 으로 표현을 해주고, 이어져 있지 않다면 단독 숫자로 표현을 해주면 되는 문제이다. 그렇기 때문에 일단 while 문을 사용해서 nums에 숫자가 있을 때 진행을 해주었다. nums에 아무것도 없다면 자동으로 빈 배열이 출력된다. 만약 nums가 비어있지 않다면, 하나의 while문을 더 검사한다. end + 1 < len(nums)은 현재 검사하는 숫자가 배열의 맨 마지막 숫자가 아닌지 검사하는 용도이다. nums[end+1] == nums[end] + 1은 그 다음 숫자가 또 이어지는 지 검사하는 용도이다. 이 while문을 통과한다면 다음 배열 숫자가 이어지는 숫자라는 것이므로 end += 1을 해준다. 이 while이 끝난다면 이 다음에 이어지는 숫자가 오지 않다는다는 뜻이므로 answer에 start와 end 값을 이용해 append해준다. 하지만 이 때 단독 숫자일 수 있으므로 start와 end가 같은지 검사를 꼭 해줘야한다.