228. Summary Ranges
You are given a sorted unique integer array
nums.A range
[a,b]is the set of all integers fromatob(inclusive).Return the smallest sorted list of ranges that cover all the numbers in the array exactly. That is, each element of
numsis covered by exactly one of the ranges, and there is no integerxsuch thatxis 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 == bExample 1:
Input: nums = [0,1,2,4,5,7]
Output: ["0->2","4->5","7"]
Explanation: The ranges are:
[0,2] --> "0->2"
[4,5] --> "4->5"
[7,7] --> "7"Example 2:
Input: nums = [0,2,3,4,6,8,9]
Output: ["0","2->4","6","8->9"]
Explanation: The ranges are:
[0,0] --> "0"
[2,4] --> "2->4"
[6,6] --> "6"
[8,9] --> "8->9"
def summaryRanges(self, nums: List[int]) -> List[str]:
res = []
if not nums:
return res
start = nums[0]
end = nums[0]
for n in nums[1:]:
if n == end + 1:
end = n
else:
if start == end:
res.append(str(start))
else:
res.append(str(start) + "->" + str(end))
start = n
end = n
if start == end:
res.append(str(start))
else:
res.append(str(start) + "->" + str(end))
return res