您的位置:首页 > 其它

Leetcode: Summary Ranges

2015-08-26 10:31 113 查看

Question

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

Credits:

Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.

Show Tags

Show Similar Problems

Solution

Code

[code]class Solution(object):
    def summaryRanges(self, nums):
        """
        :type nums: List[int]
        :rtype: List[str]
        """
        res = []
        if nums==[]:
            return res

        start, stop = nums[0], nums[0]
        for ind in range(1,len(nums)):
            if nums[ind]==(nums[ind-1]+1):
                stop = nums[ind]
            else:
                res.append(self.helper(start, stop))
                start, stop = nums[ind], nums[ind]

        res.append(self.helper(start, stop))
        return res

    def helper(self, start, stop):
        cur = str(start)
        if start!=stop:
            cur = cur + '->' + str(stop)

        return cur


Error Path

did not consider the case that len(nums)==1. should be careful for the smaller case

forget to return !!!!!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: