435. Non-overlapping Intervals
Given a collection of intervals, find the minimum number of intervals you need to remove to make the rest of the intervals non-overlapping.
Note:
You may assume the interval’s end point is always bigger than its start point.
Intervals like [1,2] and [2,3] have borders “touching” but they don’t overlap each other.
Example 1:
Input: [ [1,2], [2,3], [3,4], [1,3] ]
Output: 1
Explanation: [1,3] can be removed and the rest of intervals are non-overlapping.
Example 2:
Input: [ [1,2], [1,2], [1,2] ]
Output: 2
Explanation: You need to remove two [1,2] to make the rest of intervals non-overlapping.
Example 3:
Input: [ [1,2], [2,3] ]
Output: 0
Explanation: You don’t need to remove any of the intervals since they’re already non-overlapping.
题目内容:
题目给出一个数组,数组每个元素代表一个区间。这些区间可能会有重叠,我们可以去除其中的一些区间,使得他们不重叠,题目要求我们求出去除区间的最少数量。
解题思路:
首先对这些区间按照开始时间进行升序排序。开始以排序后的第一个区间的结束时间作为标志currentEnd,那么当访问下一个区间的时候,有2种情况:
- 如果下一个区间与他没有重叠,那么更新currentEnd更新为下一个区间的结束时间。
- 如果下一个区间与他有重叠,那么需要去掉其中一个,那么肯定是去除结束时间比较晚的,这样才能降低保留的那个区间与下一个区间重合的可能性。
代码:
这里写代码片//
// main.cpp
// 435. Non-overlapping Intervals
//
// Created by mingjc on 2017/4/16.
// Copyright © 2017年 mingjc. All rights reserved.
//
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
#define MIN(a, b) (a < b ? a : b)
/**
* 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:
int eraseOverlapIntervals(vector<Interval>& intervals) {
if (intervals.size() <= 1) return 0;
sort(intervals.begin(), intervals.end(), compare);
int result = 0;
int currentEnd = intervals[0].end;
for (int i = 1; i < intervals.size(); i++) {
if (intervals[i].start < currentEnd) {
currentEnd = MIN(currentEnd, intervals[i].end);
result++;
}
else {
currentEnd = intervals[i].end;
}
}
return result;
}
static bool compare(Interval i0, Interval i1) {
return i0.start < i1.start;
}
};
int main(int argc, const char * argv[]) {
// insert code here...
std::cout << "Hello, World!\n";
return 0;
}