You are given a sorted unique integer array
nums
.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 integerx
such thatx
is in one of the ranges but not innums
.Each range
[a,b]
in the list should be output as:
"a->b"
ifa != b
"a"
ifa == b
class Solution:
def summaryRanges(self, nums):
if not nums:
return []
i, j = 0, 0
res = []
while j < len(nums) - 1:
# 连续数字
if nums[j] + 1 == nums[j + 1]:
j += 1
else:
# 单独一个数字
if i == j:
res.append(str(nums[j]))
i += 1
j += 1
# 头尾放进 res
else:
res.append(str(nums[i]) + '->' + str(nums[j]))
i, j = j + 1, j + 1
# 退出循环后最后一组
if i == j:
res.append(str(nums[j]))
else:
res.append(str(nums[i]) + '->' + str(nums[j]))
return res