leetcode with python:228. Summary Ranges

题目:

You are given a sorted unique integer array nums.

A range [a,b] is the set of all integers from a to b (inclusive).

Return the smallest sorted list of ranges that cover all the numbers in the array exactly. That is, each element of nums is covered by exactly one of the ranges, and there is no integer x such that x is in one of the ranges but not in nums.

Each range [a,b] in the list should be output as:

"a->b" if a != b
"a" if a == b

给定一个阵列,将里面连续的整数依题目要求变为range表示后回传
ex:input:[0,2,3,4,6,8,9]=>output:["0","2->4","6","8->9"]
explanation:
[0,0] --> "0"
[2,4] --> "2->4"
[6,6] --> "6"
[8,9] --> "8->9"

这题我稍微採取了双指标的概念实作

class Solution:    def summaryRanges(self, nums: List[int]) -> List[str]:        ans=[]        i=0        j=0        while j<len(nums):            if j<len(nums)-1 and nums[j+1]-nums[j]==1:                j=j+1            else:                if i==j:                    ans.append(str(nums[j]))                    j=j+1                    i=j                else:                    ans.append(str(nums[i])+"->"+str(nums[j]))                    j=j+1                    i=j        return ans

两指标都放在阵列之始(i,j)
假如下一项比前一项多1(即连续),j继续往前
反之,则开始"结算"
若i和j位置不同,代表出现了range,起终点刚好是nums[i]和nums[j]
我们依题目要求append"nums[i]->nums[j]"
若i和j位置相同,代表没有range,append"nums[j]"即可
如此判断直到阵列尾端
特别注意j走到尾端时就一定要"结算"了
要特别做个条件式判断
最后执行时间27ms(faster than 97.50%)

那我们下题见


关于作者: 网站小编

码农网专注IT技术教程资源分享平台,学习资源下载网站,58码农网包含计算机技术、网站程序源码下载、编程技术论坛、互联网资源下载等产品服务,提供原创、优质、完整内容的专业码农交流分享平台。

热门文章