Summary Ranges
Problem
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"
ifa != b
"a"
ifa == b
Constraints
0 <= nums.length <= 20
-231 <= nums[i] <= 231 - 1
- All the values of
nums
are unique. nums
is sorted in ascending order.
Solution
The problem Summary Ranges
can be solved by repeating a process of recording a start index and expanding the range until a non-consecutive element is found.
Implementation
class Solution
{
public:
vector<string> summaryRanges(vector<int> &nums)
{
vector<string> ret;
for (int i = 0; i < nums.size(); i++)
{
int idx = i;
while (i < nums.size() - 1 && nums[i + 1] == nums[i] + 1)
i++;
if (nums[idx] == nums[i])
ret.push_back(to_string(nums[idx]));
else
ret.push_back(to_string(nums[idx]) + "->" + to_string(nums[i]));
}
return ret;
}
};