LeetCode 253 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.

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

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

Solution1

  • Sort given intervals by start time
  • Use a heap to get the interval with earliest end time. Assign a new room if not able to merge two intervals together
  • Beats over 70% submissions
/**
 * 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() {
            public int compare(Interval i1, Interval i2) {
                return i1.start - i2.start;
            }
        });
        PriorityQueue pq = new PriorityQueue(new Comparator() {
            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

  • Inspiring solution https://leetcode.com/problems/meeting-rooms-ii/discuss/67855/Explanation-of-%22Super-Easy-Java-Solution-Beats-98.8%22-from-%40pinkfloyda
  • Put start time and end time into two arrays and get them sorted
  • Basically, it use a pointer to maintain minimum value of next end time as a simulation of poll() element in PriorityQueue
  • Beats over 100% submissions


    image.png
/**
 * 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

Follow-up

Most frequent time range

你可能感兴趣的:(LeetCode 253 Meeting Rooms II)