本题题目要求如下:
Given a sorted integer array without duplicates, return the summary of its ranges.
For example, given [0,1,2,4,5,7]
, return ["0->2","4->5","7"].
class Solution {
public:
vector<string> summaryRanges(vector<int>& nums) {
vector<string> res;
if (nums.empty()) {
return res;
}
int start = nums[0];
int end = nums[0];
for (int i = 1; i < nums.size(); ++i) {
if (nums[i] == end + 1) {
++end;
}
else {
if (start != end) {
res.push_back(to_string(start) + "->" + to_string(end));
}
else {
res.push_back(to_string(end));
}
start = nums[i];
end = nums[i];
}
}
if (start != end) {
res.push_back(to_string(start) + "->" + to_string(end));
}
else {
res.push_back(to_string(end));
}
return res;
}
};