LeetCode刷题实战228:汇总区间
You are given a sorted unique integer array nums.
Return the smallest sorted list of ranges that cover all the numbers in the array exactly. That is, each element of nums is covered by exactly one of the ranges, and there is no integer x such that x is in one of the ranges but not in nums.
示例
示例 1:
输入:nums = [0,1,2,4,5,7]
输出:["0->2","4->5","7"]
解释:区间范围是:
[0,2] --> "0->2"
[4,5] --> "4->5"
[7,7] --> "7"
示例 2:
输入:nums = [0,2,3,4,6,8,9]
输出:["0","2->4","6","8->9"]
解释:区间范围是:
[0,0] --> "0"
[2,4] --> "2->4"
[6,6] --> "6"
[8,9] --> "8->9"
示例 3:
输入:nums = []
输出:[]
示例 4:
输入:nums = [-1]
输出:["-1"]
示例 5:
输入:nums = [0]
输出:["0"]
解题
class Solution {
public:
vector<string> summaryRanges(vector<int>& nums) {
vector<string> r;
if(nums.size()==0) return r;
int a = nums[0];
int c = nums[0];
bool b = true;
for(int i= 1;i<nums.size();i++)
{
if(c+1 == nums[i])
{
c = nums[i];
}
else
{
if(b){
if(c == a)
{
r.push_back(to_string(a));
b = false;
i--;
}
else
{
r.push_back(to_string(a)+"->"+to_string(c));
b = false;
i--;
}
}
else{
a = nums[i];
c = nums[i];
b = true;
}
}
}
if(b){
if(c == a)
{
r.push_back(to_string(a));
b = false;
}
else
{
r.push_back(to_string(a)+"->"+to_string(c));
}
}
return r;
}
};