Sort by ends. count overlaps


  • 1
    A

    The solution is similar to solutions in the discussion. We need to sort intervals by their ends then starts. Now we can count the number of intervals which overlaps.

    public class Solution {
        public int eraseOverlapIntervals(Interval[] intervals) {
            if (intervals==null || intervals.length==0) return 0;
            
            Arrays.sort(intervals, new Comparator<Interval>() {
                @Override
                public int compare(Interval i1, Interval i2) {
                    int res = i1.end - i2.end;
                    if (res==0) res = i2.start - i1.start;
                    return res;
                }
            });
            
            int counter = 0;
            int end = intervals[0].end;
            for (int i=1; i<intervals.length; i++) {
                if (intervals[i].start>=end) {
                    end = intervals[i].end;
                } else {
                    counter++;
                }
            }
            return counter;
        }
    }
    

Log in to reply
 

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