# LeetCode435. Non-overlapping Intervals（贪心 / 动态规划）

## LeetCode435. Non-overlapping Intervals（贪心 / 动态规划）

• Medium
• Accepted：36,286
• Submissions：87,349

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:

1. You may assume the interval's end point is always bigger than its start point.
2. 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.

### 链接

https://leetcode.com/problems/non-overlapping-intervals

### 代码

• Runtime: 12 ms, faster than 86.40% of C++ online submissions for Non-overlapping Intervals.
• Memory Usage: 9.8 MB, less than 73.08% of C++ online submissions for Non-overlapping Intervals.
bool cmp(const Interval & a, const Interval & b)
{
if (a.end != b.end)
return a.end < b.end;
return a.start < b.start;
}

class Solution {
public:
int eraseOverlapIntervals(vector<Interval>& intervals) {
int n = intervals.size();
if (n == 0)
return 0;
sort(intervals.begin(), intervals.end(), cmp);
int pre = 0, ans = 1;
for (int i = 1; i < n; ++i)
{
if (intervals[i].start >= intervals[pre].end)
{
++ans;
pre = i;
}
}
return n - ans;
}
};
• Runtime: 396 ms, faster than 5.18% of C++ online submissions for Non-overlapping Intervals.
• Memory Usage: 9.9 MB, less than 15.38% of C++ online submissions for Non-overlapping Intervals.
bool cmp(const Interval & a, const Interval & b)
{
if (a.start != b.start)
return a.start < b.start;
return a.end < b.end;
}

class Solution {
public:
int eraseOverlapIntervals(vector<Interval>& intervals) {
int n = intervals.size();
if (n == 0)
return 0;
sort(intervals.begin(), intervals.end(), cmp);
vector <int> dp(n + 1, 1);
for (int i = 1; i < n; ++i)
{
for (int j = 0; j < i; ++j)
{
if (intervals[i].start >= intervals[j].end)
dp[i] = max(dp[i], dp[j] + 1);
}
}
int ans = 0;
for (int i = 0; i < n; ++i)
ans = max(ans, dp[i]);
return n - ans;
}
};

The end.
2019年4月11日 星期四