力扣链接:https://leetcode-cn.com/probl…
解题思路:
- 这道题整体上自身比较简单,然而要解决的边界条件绝对比拟多
- 数组是排序的,那么在[lower, upper]这个区间中,如果没有缺失数字/区间的话,实践上每个数字都应该是相邻的,那么就能够从lower做为终点,顺次进行遍历,如果数组中的数字大于lower开始的游标(每次比拟完lower加一),那么就阐明有缺失,此时的缺失能够分为两种状况:(1)只缺失了一个数字,那么lower就等于nums[i] – 1 (2)缺失多个数字:lower 就小于nums[i] – 1.
- 最初整个数组遍历完结之后,游标此刻指向数组最初一个数+1,然而upper不肯定和最初一个数相等,也有可能大于最初一个数字,那么这个时候就须要比拟游标和upper的大小,如果相等则将upper退出,如果upper大于l,那么退出l->upper
class Solution {
public:
vector<string> findMissingRanges(vector<int>& nums, int lower, int upper) {
long l = lower;
vector<string> ans;
for(int i = 0; i < nums.size(); ++i)
{
if(l == nums[i])
l++;//相等,我跳过你
else if(l < nums[i])
{ //有空缺
if(l < nums[i]-1)//大于1
ans.push_back(to_string(l)+"->"+to_string(nums[i]-1));
else if(l == nums[i]-1)//等于1
ans.push_back(to_string(l));
l = long(nums[i])+1;//更新l到nums[i]下一个数
// [2147483647]
// 0
// 2147483647
}
}
if(l < upper)
ans.push_back(to_string(l)+"->"+to_string(upper));
else if(l==upper)
ans.push_back(to_string(l));
return ans;
}
};
发表回复