Greedy Java Concise


  • 0
    public class Solution { // greedy
        public int eraseOverlapIntervals(Interval[] intervals) {
            if (intervals == null || intervals.length == 0) return 0;
            Arrays.sort(intervals, new Comparator<Interval>(){
                public int compare(Interval a, Interval b) {
                    return a.start == b.start ? a.end - b.end : a.start - b.start;
                }
            });
            int res = 0;
            Interval temp = intervals[0];
            for (int i = 1; i < intervals.length; i++) {
                Interval curr = intervals[i];
                if (curr.start >= temp.end) {
                    temp = curr;
                }
                else {
                    res++;
                    if (curr.end < temp.end) temp = curr;
                }
            }
            return res;
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.