# 228. Summary Ranges ###### tags: `Python`,`Leetcode` https://leetcode.com/problems/summary-ranges/description/ ## MyCode ``` python = class Solution: def summaryRanges(self, nums: List[int]) -> List[str]: ans = [] idx = 0 while idx < len(nums): start = nums[idx] while idx + 1 < len(nums) and nums[idx] + 1 == nums[idx+1]: idx += 1 if start != nums[idx]: ans.append(str(start) + "->" + str(nums[idx])) else: ans.append(str(start)) idx += 1 return ans ``` ## 題目敘述 * 題目給一個由小到大排序 list `nums` ,題目要求分段輸出 list 的 range ,每段 range 中不可包含不在 `nums` 中的元素 * 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" ``` ### 直覺 * 就遍歷 `nums` 裡面的數, 如果 nums[i]+1 == nums [i+1],表示可以概括到同一個 range ,所以我要找到這 range 的尾,才可以輸出 1. 如果 nums[i]+1 != nums [i+1],他就是尾 * 如果 nums[i] 跟前一個後一個都不連續,直接輸出即可