LeetCode 253 Meeting Rooms II

2018-10-21  本文已影响0人  manayuan

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.

Example 1:
Input: [[0, 30],[5, 10],[15, 20]]
Output: 2

Example 2:
Input: [[7,10],[2,4]]
Output: 1

Solution1

/**
 * 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; }
 * }
 */
class Solution {
    public int minMeetingRooms(Interval[] intervals) {
        Arrays.sort(intervals, new Comparator<Interval>() {
            public int compare(Interval i1, Interval i2) {
                return i1.start - i2.start;
            }
        });
        PriorityQueue<Interval> pq = new PriorityQueue(new Comparator<Interval>() {
            public int compare(Interval i1, Interval i2) {
                return i1.end - i2.end;
            }
        });
        for (Interval interval : intervals) {
            Interval tmp = pq.poll();
            if (tmp == null || interval.start < tmp.end) {
                pq.offer(interval);
                if (tmp == null) continue;
            }
            else {
                tmp.end = interval.end;
            }
            pq.offer(tmp);
        }
        return pq.size();
    }
}

Solution2

/**
 * 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; }
 * }
 */
class Solution {
    public int minMeetingRooms(Interval[] intervals) {
        int[] start = new int[intervals.length];
        int[] end = new int[intervals.length];
        for (int i=0; i<intervals.length; i++) {
            start[i] = intervals[i].start;
            end[i] = intervals[i].end;
        }
        Arrays.sort(start);
        Arrays.sort(end);
        int room = 0, ptr = 0;
        for (int i=0; i<start.length; i++) {
            if (start[i] < end[ptr]) {
                room ++;
            }
            else {
                ptr ++;
            }
        }
        return room;
    }
}

Follow-up

Most frequent time range

上一篇下一篇

猜你喜欢

热点阅读