【每日一题】【LeetCode】【第十九天】【Python】汇总区间
阿里云国内75折 回扣 微信号:monov8 |
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6 |
解决之路= =
题目描述
测试案例部分
第一次
没有想到什么更快的方法先用两个循环来写出来思路。
class Solution(object):
def summaryRanges(self, nums):
res = []
index = 0
n = len(nums)
while index < n:
if index == n - 1:
res.append(str(nums[index]))
break
else:
left = index
while nums[index] == nums[index + 1] - 1:
index += 1
if left == index:
res.append(str(nums[left]))
else:
res.append(str(nums[left]) + "->" + str(nums[index]))
index += 1
return res
LeetCode的python环境好像不支持
f"{XX}->{XX}"
这样的写法会报语法错误所以这里还是用str()
强转型然后字符串拼接完成。
测试正确提交却错误报错为超出下标范围。
第二次
既然会越界略微修改一下第二轮的while循环就好了。
class Solution(object):
def summaryRanges(self, nums):
res = []
index = 0
n = len(nums)
while index < n:
if index == n - 1:
res.append(str(nums[index]))
break
else:
left = index
while index < n - 1:
if nums[index] == nums[index + 1] - 1:
index += 1
else:
break
if left == index:
res.append(str(nums[left]))
else:
res.append(str(nums[left]) + "->" + str(nums[index]))
index += 1
return res
第二轮的while循环的条件为什么不是index < n
而是index < n - 1
因为如果允许n-1
进入第二轮的whileif条件判断时就会越界。
那么少的那一次怎么判断呢交给第一轮循环的if判断去处理。
# 就是这段代码
if index == n - 1:
res.append(str(nums[index]))
break
测试正确提交成功。
耗时也还可以可以算结束啦。
杂谈
过年啦断更到27号28号继续更新。