Non-overlapping Intervals

https://www.lintcode.com/problem/non-overlapping-intervals/description

import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * Definition of Interval:
 * public classs Interval {
 * int start, end;
 * Interval(int start, int end) {
 * this.start = start;
 * this.end = end;
 * }
 * }
 */

public class Solution {
    /**
     * @param intervals: a collection of intervals
     * @return: the minimum number of intervals you need to remove
     */
    public int eraseOverlapIntervals(List intervals) {
        // write your code here
        Collections.sort(intervals, new Comparator() {
            @Override
            public int compare(Interval o1, Interval o2) {
                if (o1.start == o2.start) {
                    return o1.end - o2.end;
                }
                return o1.start - o2.start;
            }
        });
        int result = 0;
        for (int i = 0; i < intervals.size() - 1; i++) {
            Interval now = intervals.get(i);
            Interval next = intervals.get(i + 1);
            if (now.end <= next.start) {
                continue;
            }
            if (now.end <= next.end) {
                intervals.remove(next);
            } else {
                intervals.remove(now);
            }
            i--;
            result++;
        }
        return result;
    }
}

你可能感兴趣的:(Non-overlapping Intervals)