-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSummaryRanges.cpp
36 lines (33 loc) · 950 Bytes
/
SummaryRanges.cpp
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
36
/* Coding challenge #228 from LeetCode */
class Solution {
public:
vector<string> summaryRanges(vector<int>& nums) {
vector<string> result;
int i = 1;
int start = 0;
int end = 0;
if (nums.size() == 1) {
result.push_back(std::to_string(nums[0]));
return result;
}
while (i < nums.size()) {
string st = std::to_string(nums[start]);
while (nums[i] == nums[i-1] + 1) {
i++;
}
end = i - 1;
if (start != end) {
st += "->";
st += std::to_string(nums[end]);
}
result.push_back(st);
start = i;
end = i;
i++;
if (start == nums.size()-1) {
result.push_back(std::to_string(nums[start]));
}
}
return result;
}
};