题目:
Given a sorted integer array without duplicates, return the summary of its ranges.
例子
Example 1:
Input: [0,1,2,4,5,7]
Output: ["0->2","4->5","7"]
Example 2:
Input: [0,2,3,4,6,8,9]
Output: ["0","2->4","6","8->9"]
问题解析:
给定一个递增排序的数组,给出数组的范围总结。
链接:
解答:
- 问题不难,难点在于如何对数组的索引进行更新。
class Solution {
public:
vector<string> summaryRanges(vector<int>& nums) {
vector<string> ret;
if(nums.size() == 0)
return ret;
for(int i=0; i<nums.size();){
int start = i;
int end = i;
while(nums[end+1] == nums[end] + 1 && end < nums.size())
end++;
if(end == start){
ret.push_back(to_string(nums[end]));
}
else{
ret.push_back(to_string(nums[start]) + "->" + to_string(nums[end]));
}
i = end + 1;
}
return ret;
}
};