Coding Test/Python

[LeetCode] 228. Summary Ranges (easy, python)

lim.dev 2024. 1. 4. 02:19

https://leetcode.com/problems/summary-ranges/?envType=study-plan-v2&envId=top-interview-150

 

Summary Ranges - LeetCode

Can you solve this real interview question? Summary Ranges - 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 arr

leetcode.com

전체 코드

# 1:52 ~ 2:17 (25")
class Solution:
    def summaryRanges(self, nums: List[int]) -> List[str]:
        if not nums:
            return []
        
        tmp_answer = []
        pre = nums[0]
        tmp = [pre]
        for i in range(1, len(nums)):
            if (pre + 1) == nums[i]:
                pre = nums[i]
                tmp.append(nums[i])
            else:
                tmp_answer.append(tmp)
                pre = nums[i]
                tmp = [pre]
        tmp_answer.append(tmp)
        
        answer = []
        for a in tmp_answer:
            if len(a) == 1:
                answer.append(str(a[0]))
            else:
                answer.append(str(a[0])+"->"+str(a[-1]))

        return answer