美文网首页Leetcode
Leetcode 228. Summary Ranges

Leetcode 228. Summary Ranges

作者: SnailTyan | 来源:发表于2021-02-03 15:05 被阅读0次

    文章作者:Tyan
    博客:noahsnail.com  |  CSDN  |  简书

    1. Description

    Summary Ranges

    2. Solution

    • Version 1
    class Solution:
        def summaryRanges(self, nums):
            result = []
            length = len(nums)
    
            i = 0
            while i < length:
                if i == length - 1 or nums[i] + 1 != nums[i + 1]:
                    result.append(str(nums[i]))
                    i += 1
                    continue
    
                start = nums[i]
                while i + 1 < length and nums[i] + 1 == nums[i + 1]:
                    i += 1
                end = nums[i]
                result.append(str(start) + '->' + str(end))
                i += 1
    
            return result
    
    • Version 2
    class Solution:
        def summaryRanges(self, nums):
            result = []
    
            for num in nums:
                if num - 1 not in nums and num + 1 not in nums:
                    result.append(str(num))
                    continue
    
                if num - 1 not in nums:
                    start = num
    
                if num + 1 not in nums:
                    end = num
                    result.append(str(start) + '->' + str(end))
    
            return result
    

    Reference

    1. https://leetcode.com/problems/summary-ranges/

    相关文章

      网友评论

        本文标题:Leetcode 228. Summary Ranges

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