228 Summary Ranges
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"]
.
Solution
class Solution {
public:
vector<string> summaryRanges(vector<int>& nums) {
int n = nums.size();
vector<string> res;
if ( n == 0 ) return res;
if ( n == 1 ) {
res.push_back(to_string(nums[0]));
return res;
}
int start = nums[0];
nums.push_back(nums[n-1]);
for ( int i = 1; i <= n; i++ ) {
if ( nums[i] == nums[i-1] + 1 ) continue;
if ( nums[i-1] == start ) res.push_back(to_string(start));
else res.push_back(to_string(start) + "->" + to_string(nums[i-1]));
start = nums[i];
}
return res;
}
};