描述
Given a collection of intervals, find the minimum number of intervals you need to remove to make the rest of the intervals non-overlapping.
个人思路:既然要求最少移出,那么可以确定的贪心策略就是如果发生冲突,那么移出区间更长的interval,所以先排序,如果start相同,移出end更大的那个interval;另一种情况也是这样
public int eraseOverlapIntervals(List<Interval> intervals) {Collections.sort(intervals, new Comparator<Interval>() {@Overridepublic int compare(Interval o1, Interval o2) {return (o1.start == o2.start)?(o1.end-o2.end):(o1.start-o2.start);}});int size = intervals.size();for (int i = 1; i < intervals.size(); ) {if (intervals.get(i).start == intervals.get(i-1).start) {intervals.remove(i);continue;}if (intervals.get(i).start < intervals.get(i-1).end){if (intervals.get(i).end > intervals.get(i-1).end)intervals.remove(i);elseintervals.remove(i-1);continue;}i++;}return size-intervals.size();}
dalao思路:其实思路差不多,但dalao的做法更简洁,值得学习
public int eraseOverlapIntervals(List<Interval> intervals) {Collections.sort(intervals, IntervalComp.COMP);int res = 0;int lastright = Integer.MIN_VALUE;for (Interval i : intervals)if (i.start >= lastright) {lastright = i.end;} else {res++;lastright = Math.min(lastright, i.end);//谁的end更大移除谁}return res;}
summary:1、总是先选取当前对情况最优的个体处理
2、使用一个变量,避免list.remove操作(其实完全不知道怎么描述summary,先放着。。。。)