-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path228. Summary Ranges.cpp
More file actions
35 lines (27 loc) · 925 Bytes
/
228. Summary Ranges.cpp
File metadata and controls
35 lines (27 loc) · 925 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
31
32
33
34
35
class Solution {
public:
vector<string> summaryRanges(vector<int>& nums) {
vector<string> res;
if (nums.empty()) return res;
int start = nums[0]; // start of current range
int end = nums[0]; // end of current range
for (int i = 1; i < nums.size(); ++i) {
if (nums[i] == end + 1) {
end = nums[i];
} else {
if (start == end) {
res.push_back(to_string(start));
} else {
res.push_back(to_string(start) + "->" + to_string(end));
}
start = end = nums[i];
}
}
if (start == end) {
res.push_back(to_string(start));
} else {
res.push_back(to_string(start) + "->" + to_string(end));
}
return res;
}
};