[LeetCode] Summary Ranges

228. Summary Ranges

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 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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class Solution {
public:
vector<string> summaryRanges(vector<int>& nums) {
vector<int> range;
vector<string> res;
for(auto n : nums) {
if(range.empty()) {
range.push_back(n);
range.push_back(n);
} else if(range.back() + 1 == n) {
range.back() = n;
} else {
if(range[0] == range[1]) res.push_back(to_string(range.back()));
else res.push_back(to_string(range[0])+"->"+to_string(range[1]));
range.clear();
range.push_back(n);
range.push_back(n);
}
}
if(!range.empty()) {
if(range[0] == range[1]) res.push_back(to_string(range.back()));
else res.push_back(to_string(range[0])+"->"+to_string(range[1]));
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/28/PS/LeetCode/summary-ranges/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.