前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >LeetCode 163. 缺失的区间

LeetCode 163. 缺失的区间

作者头像
Michael阿明
发布2020-07-13 14:53:06
1.1K0
发布2020-07-13 14:53:06
举报
文章被收录于专栏:Michael阿明学习之路

1. 题目

给定一个排序的整数数组 nums ,其中元素的范围在 闭区间 [lower, upper] 当中,返回不包含在数组中的缺失区间。

代码语言:javascript
复制
示例:

输入: nums = [0, 1, 3, 50, 75], lower = 0 和 upper = 99,
输出: ["2", "4->49", "51->74", "76->99"]

来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/missing-ranges 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

2. 解题

代码语言:javascript
复制
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;
    }
};

4 ms 7.2 MB

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2020/07/07 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 1. 题目
  • 2. 解题
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档