---
# System prepended metadata

title: 228. Summary Ranges (medium)
tags: [online_judge, python3]

---

# 228. Summary Ranges (medium)

###### tags: `online_judge`, `python3`

難度只能算在 easy 級別，但題目內藏陷阱。放 medium... 也算合理吧。

把數列中連續的數字分到同一組去。

直接遍歷一次，記錄各段連續的數字的起點及終點即可。

注意題目並沒有給出數列範圍，數列可能為空。能避過這點一發入魂的，才能算是及格通過吧。

---

### 題目

```
Given a sorted integer array without duplicates, return the summary of its ranges.

Example 1:

Input:  [0,1,2,4,5,7]
Output: ["0->2","4->5","7"]
Explanation: 0,1,2 form a continuous range; 4,5 form a continuous range.

Example 2:

Input:  [0,2,3,4,6,8,9]
Output: ["0","2->4","6","8->9"]
Explanation: 2,3,4 form a continuous range; 8,9 form a continuous range.
```

---

### 解答
```python=
class Solution:
    def summaryRanges(self, nums) :
        if not nums:
            return nums
        ans = []
        count = 1
        start = nums[0]
        end = nums[0]
        for i in range(1,len(nums)):
            
            if end == nums[i] - 1:
                count += 1
                end = nums[i]
            else:
                if count == 1:
                    ans.append(str(start))
                else:
                    ans.append(str(start) + "->" + str(end))
                    
                count = 1
                start = nums[i]
                end = nums[i]
        
        if count == 1:
            ans.append(str(start))
        else:
            ans.append(str(start) + "->" + str(end))
        
        return ans
        
a = Solution()
print (a.summaryRanges([0,1,2,4,5,7]))
print (a.summaryRanges([0,2,3,4,6,8,9]))
print (a.summaryRanges([]))
        
```

---
### 成績

![](https://i.imgur.com/BgOPRy1.png)

---