?LeetCode刷題實(shí)戰(zhàn)228:匯總區(qū)間
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"]
解釋:區(qū)間范圍是:
[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"]
解釋:區(qū)間范圍是:
[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;
}
};
LeetCode1-220題匯總,希望對(duì)你有點(diǎn)幫助!
LeetCode刷題實(shí)戰(zhàn)221:最大正方形
LeetCode刷題實(shí)戰(zhàn)222:完全二叉樹的節(jié)點(diǎn)個(gè)數(shù)
LeetCode刷題實(shí)戰(zhàn)223:矩形面積
LeetCode刷題實(shí)戰(zhàn)224:基本計(jì)算器
LeetCode刷題實(shí)戰(zhàn)225:用隊(duì)列實(shí)現(xiàn)棧
LeetCode刷題實(shí)戰(zhàn)226:翻轉(zhuǎn)二叉樹
LeetCode刷題實(shí)戰(zhàn)227:基本計(jì)算器 II
