[leetcode/matrix](sort)Insert Interval(库函数sort的运用)

6 篇文章 0 订阅
4 篇文章 0 订阅

库函数sort的运用

题干:

Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessary). You may assume that the intervals were initially sorted according to their start times.

Example 1:

Input: intervals = [[1,3],[6,9]], newInterval = [2,5]
Output: [[1,5],[6,9]]

Example 2:

Input: intervals = [[1,2],[3,5],[6,7],[8,10],[12,16]], newInterval = [4,8]
Output: [[1,2],[3,10],[12,16]]

Explanation: Because the new interval [4,8] overlaps with [3,5],[6,7],[8,10].
Please submit a cpp file with the implementation of function

vector<Interval> insert(vector<Interval>& intervals, Interval newInterval) 

you can start like this:

vector<Interval> Solution::insert(vector<Interval>& intervals, Interval newInterval) {}

题解

① 使用sort进行代码排序,cmp比较条件是,start小的排前面
② 根据intervals里面end的情况决定直接修改最后一个intervals的end还是push_back进去

代码

#include"Solution.h"
#include<algorithm>
using namespace std;
static bool cmp(Interval& a, Interval& b){
	return a.start<b.start; //按照左端点的顺序排队 
}

vector<Interval> Solution::insert(vector<Interval>& intervals, Interval newInterval) {
	vector<Interval> ret; //要返回的区间
	intervals.push_back(newInterval);
	sort(intervals.begin(),intervals.end(),cmp);
	
	int count=0;//记录区间的数目
	ret.push_back(intervals[0]);
	
	int size=intervals.size();
	
	for(int i=1;i<size;i++){
		int& end=ret[count].end;
		
		if(intervals[i].end<=end){
			continue;
		}
		else{
			if(intervals[i].start<=end){
				end=intervals[i].end;
			}
			else{
				count++;
				ret.push_back(intervals[i]);
			}
		}
	} 
	
	return ret;
}

总结

刚开始想着分情况,start,end分别落在区间里和区间外的情况,后来感觉考虑的情形太多有点乱了。
这个方法的好处是先根据start来排序,然后再根据end进行处理,简化了分类情况

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值