228. 汇总区间
为保证权益,题目请参考 228. 汇总区间(From LeetCode).
解决方案1
CPP
C++
#include <algorithm>
#include <iostream>
#include <queue>
#include <string>
#include <vector>
using namespace std;
class Solution {
public:
vector<string> summaryRanges(vector<int> &nums) {
vector<string> ans;
{
int startIdx = 0;
while (startIdx < nums.size()) {
int endNum = nums[startIdx];
int endIdx = startIdx;
while (endIdx + 1 < nums.size() && nums[endIdx + 1] == endNum + 1) {
endIdx += 1;
endNum += 1;
}
if (endIdx == startIdx) {
ans.push_back(to_string(nums[startIdx]));
} else {
ans.push_back(to_string(nums[startIdx]) + "->" +
to_string(nums[endIdx]));
}
startIdx = endIdx + 1;
}
}
return ans;
}
};
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
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