Thursday, December 3, 2015

[leetcode] meeting room

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
/**
 * Definition for an interval.
 * public class Interval {
 *     int start;
 *     int end;
 *     Interval() { start = 0; end = 0; }
 *     Interval(int s, int e) { start = s; end = e; }
 * }
 */
public class Solution {
    public boolean canAttendMeetings(Interval[] intervals) {
        if (intervals.length <= 1) return true;
        PriorityQueue<Interval> queue = new PriorityQueue<Interval>(intervals.length, 
                                        new Comparator<Interval>(){
                                            public int compare(Interval i, Interval k){
                                                return i.start-k.start;
                                            }
                                        });
        queue.addAll(Arrays.asList(intervals));
        Interval prev = queue.poll();
        while (!queue.isEmpty()){
            Interval temp = queue.poll();
            if(isOverlap(temp, prev)) return false;
            prev = temp;
        }
        
        return true;
    }
    
    boolean isOverlap (Interval i, Interval b){
        return !(i.start >= b.end || b.start >= i.end);
    }
}

No comments:

Post a Comment