class Solution {
public:
vector<string> summaryRanges(vector<int>& nums) {
int n = nums.size();
if(n == 0){
return {};
}
if(n == 1){
return {to_string(nums[0])};
}
vector<string> res;
int l = 0, r = 0;
for(int i = 1; i < n; ++i){
if(nums[i - 1] != nums[i] - 1){
if(l == r){
res.push_back(to_string(nums[l]));
}else{
res.push_back(to_string(nums[l]) + "->" + to_string(nums[r]));
}
l = r = i;
}else{
++r;
}
}
if(nums[n - 2] == nums[n - 1] - 1){
res.push_back(to_string(nums[l]) + "->" + to_string(nums[r]));
}else{
res.push_back(to_string(nums[r]));
}
return res;
}
};
官方的明显更简洁。。。
class Solution {
public:
vector<string> summaryRanges(vector<int>& nums) {
int n = nums.size();
vector<string> res;
int i = 0;
while(i < n){
int l = i;
++i;
while(i < n && nums[i] == nums[i - 1] + 1) ++i;
int r = i - 1;
if(l == r){
res.push_back(to_string(nums[l]));
}else{
res.push_back(to_string(nums[l]) + "->" + to_string(nums[r]));
}
}
return res;
}
};