Simple AC Java solution - based on Merge Intervals idea


  • 0
    H

    Sort intervals via comparator, and then do merge intervals. In for loop, if intervals overlapping, return false directly. On the end, if res.size() <=1, return true, else return false.

    Two test case:
    1. [[0, 30],[39, 50],[35, 40]] =>[[0 ,40] [39,50]] => false
    2. [[0, 30],[40, 50],[35, 40]] =>[[0, 50]] => true

    Any suggestions or comments ?

    private Comparator<Interval> comparator = new Comparator<Interval> () {
        @Override public int compare(Interval x, Interval y) {
            return x.start - y.start;
        }
    };
    
    
    public boolean canAttendMeetings(Interval[] intervals) { 
    
        if (intervals == null || intervals.length ==0) return true;
           List<Interval> res = new ArrayList<Interval>();
        
        Arrays.sort(intervals, comparator);
        int start = intervals[0].start, end= intervals[0].end;
        
        for(int i=1 ; i< intervals.length; i++) {
            if (intervals[i].start >= end) {
                end = intervals[i].end;  // move the end to next end
            } else {
                return false;   // overlapping intervals 
            }
        }
        res.add(new Interval(start, end));
        return res.size() <= 1?  true : false;
    }

Log in to reply
 

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