leetcode228. Summary Ranges

题目描述(难度(Medium)):

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"].

Tags: Array
Similar Problems: (M) Missing Ranges (H) Data Stream as Disjoint Intervals

分析:求解数组里数字的范围,数组告知已经是有序的并且没有重复值,为了方便处理,我们在数组最后添加一个元素

代码实现:

class Solution(object):
    def summaryRanges(self, nums):
        """
        :type nums: List[int]
        :rtype: List[str]
        """
        n = len(nums)
        if n == 0:
            return []
        result = []
        startIdx = 0
        nums.append(nums[-1])#方便后面处理
        for i in range(n):
            if nums[i]==nums[i+1]-1:
                continue
            else:
                if i==startIdx:
                    result.append(str(nums[i]))
                else:
                    result.append(str(nums[startIdx])+"->"+str(nums[i]))
                startIdx = i+1
        return result



你可能感兴趣的:(leetcode)