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 was always bigger than it start point. intervals like [to] and [2,3] has borders "touching" but they don ' t overlap each other. Example 1: Input: [[[2,3], [3,4], [1,3]]output:1Explanation: [1,3] can be removed and the rest of intervals is non-overlapping. Example2: Input: [[[Up], []]output:2explanation:you need to remove both [To make the rest of intervals non-overlapping. Example3: Input: [[[2,3], []]output:0explanation:you Don' t need to remove any of the intervals since they ' re already non-overlapping.
Actually, the problem is the same as "Given a collection of intervals, find the maximum number of intervals that was Non-o Verlapping. " (The classic greedy problem:interval scheduling). With the solution to this problem, guess how do we get the minimum number of intervals to remove? : )
Sorting interval.end in ascending order was O (NLOGN), then traverse intervals array to get the maximum number of Non-overla pping intervals is O (n). Total is O (NLOGN).
At the beginning to think of a fork, thought is to ask for the same time overlap the most interval number, but think carefully to find that the wrong, should be non-overlap interval the maximum number
1 /**2 * Definition for an interval.3 * public class Interval {4 * int start;5 * int end;6 * Interval () {start = 0; end = 0;}7 * Interval (int s, int e) {start = s; end = e;}8 * }9 */Ten Public classSolution { One Public interaseoverlapintervals (interval[] intervals) { A if(Intervals.length = = 0)return0; - intNonoverlap = 1; - intSeq = 0; theArrays.sort (intervals,NewComparator<interval>() { - Public intCompare (Interval i1, Interval i2) { - returnI1.end-I2.end; - } + }); - for(intI=1; i<intervals.length; i++) { + if(Intervals[i].start >=intervals[seq].end) { ASeq =i; atnonoverlap++; - } - } - returnIntervals.length-Nonoverlap; - } -}
leetcode:non-overlapping intervals