• 第一周 Leetcode 57. Insert Interval (HARD)


    Insert interval 

    题意简述:给定若干个数轴上的闭区间,保证互不重合且有序,要求插入一个新的区间,并返回新的区间集合,保证有序且互不重合。

    只想到了一个线性的解法,所有区间端点,只要被其他区间覆盖,就是不合法的,把他们去掉后,就可以直接得到答案。设新区间为【left,right】,那么,比left小的端点显然合法,比right大的端点显然也合法,left和right之间的端点显然不合法,然后判断Left和right是否合法即可。难度不大,代码有些细节需要注意。

    /**
     * Definition for an interval.
     * struct Interval {
     *     int start;
     *     int end;
     *     Interval() : start(0), end(0) {}
     *     Interval(int s, int e) : start(s), end(e) {}
     * };
     */
    class Solution {
    public:
        vector<Interval> insert(vector<Interval>& intervals, Interval newInterval) {
           vector<int> vec;
    	   for(int i=0;i<intervals.size();i++)
    	   	{
    	   	 vec.push_back(intervals[i].start);
    	   	 vec.push_back(intervals[i].end);
    		}
    	int left=newInterval.start,right=newInterval.end;
    	bool el=true,er=true;
    	int i=0;
    	vector<int>ans;
    	while(i<vec.size()&&vec[i]<left)
    		{
    		ans.push_back(vec[i]);
    		i++;
    		}
    	i--;
    	while(i<0)i+=2;
    	if((i%2)==1) ans.push_back(left);
    	i=vec.size()-1;
    	while(i>=0&&vec[i]>right)
    		i--;
    	i++;
    	if((i%2)==0) ans.push_back(right);
    	while(i<vec.size())
    		{
    		 ans.push_back(vec[i]);
    		 i++;
    		}
     vector<Interval> anss;
     i=0;
     while(i<ans.size())
    		{
    		 Interval nn(ans[i],ans[i+1]);
    		 anss.push_back(nn);
    		 i+=2;
    		}
     return anss;
            
        }
    };
    

      

  • 相关阅读:
    Zookeeper安装
    JDK安装(Linux)
    Zookeeper简介
    修改tomcat配置解决定时任务多次重复执行
    解决.net mvc session超时的问题
    C#- JSON的操作
    Android SharedPreferences的理解与使用
    大屏适配:flexible.js的源码及配置
    charles抓包工具,抓手机端https设置
    Sanic二十:Sanic 扩展之sanic-openapi生成接口文档之sanic-openapi支持的数据类型
  • 原文地址:https://www.cnblogs.com/heisenberg-/p/6426065.html
Copyright © 2020-2023  润新知