Leetcode专题[数组]-163-缺失的区间
文章目录
力扣链接: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]下一个数
}
}
if(l < upper)
ans.push_back(to_string(l)+"->"+to_string(upper));
else if(l==upper)
ans.push_back(to_string(l));
return ans;
}
};
评论
登录后参与技术讨论,分享你的经验与见解。
登录 / 注册暂无评论