描述
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;
int i = 0;
while (i <nums.size()) {
int j = 0;
while (i + j < nums.size() && nums[i + j] - nums[i] == j) j++;
res.push_back(j == 1 ? to_string(nums[i]) : to_string(nums[i]) + "->" + to_string(nums[i + j - 1]));
i += j;
}
return res;
}
};