228. Summary Ranges
Array ·Problem Statement
link: https://leetcode.com/problems/summary-ranges/ https://leetcode.cn/problems/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
Example:
Input: nums = [0,1,2,4,5,7]
Output: ["0->2","4->5","7"]
Input: nums = [0,2,3,4,6,8,9]
Output: ["0","2->4","6","8->9"]
Solution Approach
The approach involves iterating through the sorted and unique integer array nums, identifying consecutive ranges of numbers, and formatting them into a list of strings as required by the problem statement.
Algorithm
- Iterate through the sorted and unique integer array nums.
- Identify consecutive ranges of numbers and format them as single numbers or “a->b” ranges.
- Maintain a result list, res, to collect these formatted ranges, satisfying the problem’s requirements.
Implement
class Solution:
def summaryRanges(self, nums: List[int]) -> List[str]:
l = len(nums)
if l == 0:
return []
nums.append(float('inf'))
res, start = [], 0
for i in range(l):
if nums[i + 1] != nums[i] + 1:
res.append(str(nums[i]) if i == start else "%s->%s" % (nums[start], nums[i]))
start = i + 1
return res