forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsummary-ranges.cpp
More file actions
30 lines (27 loc) · 771 Bytes
/
summary-ranges.cpp
File metadata and controls
30 lines (27 loc) · 771 Bytes
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
27
28
29
30
// Time: O(n)
// Space: O(1)
class Solution {
public:
vector<string> summaryRanges(vector<int>& nums) {
vector<string> ranges;
if (nums.empty()) {
return ranges;
}
int start = nums[0], end = nums[0];
for (int i = 1; i <= nums.size(); ++i) {
if (i < nums.size() && nums[i] == end + 1) {
end = nums[i];
} else {
auto&& range = to_string(start);
if (start != end) {
range.append("->" + to_string(end));
}
ranges.emplace_back(range);
if (i < nums.size()) {
start = end = nums[i];
}
}
}
return ranges;
}
};