Meeting Rooms II

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 list = new ArrayList();
        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;
    }
}

 

你可能感兴趣的:(Sweep,Line)