LeetCode 57. Insert Interval(插入区间)

题目描述:

    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.

例一:Given intervals [1,3],[6,9], insert and merge [2,5] in as [1,5],[6,9].
例二:Given [1,2],[3,5],[6,7],[8,10],[12,16], insert and merge [4,9] in as [1,2],[3,10],[12,16].
    This is because the new interval [4,9] overlaps with [3,5],[6,7],[8,10].

分析:
    题意:给出一些非重叠整型区间集合,插入一个新的区间,返回合并重叠区间之后的结果。
    思路:这道题跟LeetCode 56很相似,我们用一个小技巧进行转化:先把新的区间插入到所有的区间集合中去,根据区间end进行从小到大的排序,然后采用LeetCode 56的贪心算法来解决这道题。因为思路完全一致,这里不再复述算法细节。

代码:

#include <bits/stdc++.h>

using namespace std;

struct Interval{
	int start;
	int end;
	Interval(): start(0), end(0){}
	Interval(int s, int e): start(s), end(e){}
};

class Solution {
private: 
	static int cmp(const Interval a, const Interval b){
		if(a.end != b.end){
			return a.end < b.end;
		}
		return a.start < b.start;
	}

public:
    vector<Interval> insert(vector<Interval>& intervals, Interval newInterval) {
		vector<Interval> ans;
        intervals.push_back(newInterval);
		int n = intervals.size();
		// sort
		sort(intervals.begin(), intervals.end(), cmp);
		for(int i = 1; i <= n - 1; i++){
			int j = i - 1;
			while(j >= 0){
				if(intervals[j].start == -1 && intervals[j].end == -1){
					j--;
					continue;
				}
				if(intervals[i].start <= intervals[j].end){
					intervals[i].start = min(intervals[j].start, intervals[i].start);
					intervals[j].start = intervals[j].end = -1;
					j--;
				}
				else{
					break;
				}
			}
		}
		// get answer
		for(Interval p: intervals){
			if(p.start == -1 && p.end == -1){
				continue;
			}
			ans.push_back(p);
		}
		return ans;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章