美文网首页
Leetcode-228题:Summary Ranges

Leetcode-228题:Summary Ranges

作者: 八刀一闪 | 来源:发表于2016-10-08 22:13 被阅读132次

    题目

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

    思路

    用两个指针来确定一个区间

    代码

    class Solution(object):
        def summaryRanges(self, nums):
            """
            :type nums: List[int]
            :rtype: List[str]
            """
            res = []
            l = 0
            while l < len(nums):
                r = l
                while r+1<len(nums) and (nums[r+1]-nums[r])==1:
                    r += 1
                if l == r:
                    res.append(str(nums[l]))
                    l += 1
                else:
                    res.append(str(nums[l])+'->'+str(nums[r]))
                    l = r+1
            return res
    

    相关文章

      网友评论

          本文标题:Leetcode-228题:Summary Ranges

          本文链接:https://www.haomeiwen.com/subject/qkcpyttx.html