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"].
给一个排序好的数组,将相邻的数字压缩成区间的表示。
扫一遍,记录头尾,碰到后一个比前一个大超过1再处理。
代码语言:javascript复制class Solution {
public:
vector<string> summaryRanges(vector<int>& nums) {
vector<string> res;
if(nums.empty()) return res;
int s = nums[0], e = nums[0];
for(int i = 1; i < nums.size(); i )
{
if(nums[i] == nums[i - 1] 1) e = nums[i];
else
{
if(s == e) res.push_back(to_string(s));
else res.push_back(to_string(s) "->" to_string(e));
s = e = nums[i];
}
}
if(s == e) res.push_back(to_string(s));
else res.push_back(to_string(s) "->" to_string(e));
return res;
}
};