https://leetcode.com/problems/summary-ranges/
Summary Ranges
Total Accepted: 22806 Total Submissions: 114600 Difficulty: Easy
Given a sorted integer array without duplicates, return the summary of its ranges.
For example, given [0,1,2,4,5,7]
, return ["0->2","4->5","7"].
Code
class Solution(object): def summaryRanges(self, nums): """ :type nums: List[int] :rtype: List[str] """ res = [] s = "" for i, v in enumerate(nums): if i == 0: s = str(v) else: if nums[i-1] == nums[i] - 1: s = s.split("->")[0] + "->" + str(nums[i]) else: res.append(s) s = str(nums[i]) if s: res.append(s) return res
Idea:
Nothing too much.