LeetCode 56. Merge Intervals(合併重疊區間)

題目描述:

    Given a collection of intervals, merge all overlapping intervals.
    For example, given [1,3],[2,6],[8,10],[15,18], return [1,6],[8,10],[15,18].

分析:
    題意:給出一些整型區間集合,返回合併重疊區間之後的結果。
    思路:這是一道經典的貪心算法作業調度問題的變種,關鍵是把所有區間([start, end])根據end進行從小到大排序。之後進行如下操作:
    ① 對於第i個區間(i屬於1→n - 1)分別跟第j個區間(j屬於i - 1→0)逆序進行比較。Ⅰ. 如果i區間的start小於等於j區間的end,說明存在重疊現象,我們更新i區間的start爲i、j兩區間的start較小值,同時把j區間的start、end均置爲-1([-1, -1]表示該區間已經被合併,不復存在);Ⅱ. 如果i區間的start大於j區間的end,說明沒有重疊,跳出當前比較循環。

    ② 比較所有i區間(i屬於1→n - 1)之後,我們遍歷一遍0n - 1,把所有不是[-1, -1]的區間加入答案中,並返回。

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){}
};

// sort + greedy
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> merge(vector<Interval>& intervals) {
        vector<Interval> ans;
		int n = intervals.size();
		// Exceptional Case: 
		if(n == 0){
			return ans;
		}
		// 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){
					// modify
					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;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章