228. Summary Ranges

来源:互联网 发布:郝蕾骂河南人 知乎 编辑:程序博客网 时间:2024/06/01 18:34
class Solution(object):
    def summaryRanges(self, nums):
        """
        :type nums: List[int]
        :rtype: List[str]
        """
        if not nums:
            return []
        res=[]
        start=end=nums[0]
        for i in range(1,len(nums)):
            if nums[i]-nums[i-1]==1:
                end=nums[i]
            else:
                res.append(self.getStr(start,end))
                start=end=nums[i]
        res.append(self.getStr(start,end))
        return res
    def getStr(self,start,end):
        if end-start==0:
            return str(start)
        else:
            return str(start)+"->"+str(end)
原创粉丝点击