LeetCode OJ 系列之228 Summary Ranges --Python

Problem:

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

Answer:

class Solution(object):
    def summaryRanges(self, nums):
        """
        :type nums: List[int]
        :rtype: List[str]
        """
        result = []
        if len(nums) == 0:
            return result
        for index in range(len(nums)):
        	if index == 0:
        		start = nums[index]
        		continue
        	if nums[index]!=nums[index-1]+1:
        		if nums[index-1]==start:
        			result.append(str(start))
        		else:
        			result.append(str(start)+'->'+str(nums[index-1]))
        		start = nums[index]		
        
        if nums[-1] == start:
        	result.append(str(start))
        else:
        	result.append(str(start)+'->'+str(nums[-1]))
        return result
        


阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/ln152315/article/details/49861493
文章标签: LeetCode Python OJ
个人分类: LeetCode Python
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭
关闭