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;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章