Meeting Rooms II

flyatcmu發表於2016-09-11

Given an array of meeting time intervals consisting of start and end times [[s1,e1],[s2,e2],...] (si < ei), find the minimum number of conference rooms required.

For example,
Given [[0, 30],[5, 10],[15, 20]],
return 2.

思路:標準掃描線演算法,start event + 1, end event -1, 把所有的event點按照時間sort一下,如果時間相同,-1排在1前面,O(NlogN) + O(N).

class Solution {
    private class Node {
        public int time;
        public int flag;
        public Node(int time, int flag) {
            this.time = time;
            this.flag = flag;
        }
    }
    
    public int minMeetingRooms(int[][] intervals) {
        if(intervals == null || intervals.length == 0 || intervals[0].length == 0) {
            return 0;
        }
        List<Node> list = new ArrayList<Node>();
        for(int i = 0; i < intervals.length; i++) {
            list.add(new Node(intervals[i][0], 1));
            list.add(new Node(intervals[i][1], -1));
        }
        
        Collections.sort(list, (a, b) -> (
                a.time != b.time ? a.time - b.time : a.flag - b.flag));
        
        int count = 0;
        int maxcount = 0;
        for(int i = 0; i < list.size(); i++) {
            Node node = list.get(i);
            if(node.flag == 1) {
                count++;
            } else {
                count--;
            }
            maxcount = Math.max(maxcount, count);
        }
        return maxcount;
    }
}

 

相關文章