美文网首页
LeetCode 253 Meeting Rooms II

LeetCode 253 Meeting Rooms II

作者: manayuan | 来源:发表于2018-10-21 17:40 被阅读0次

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<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

相关文章

网友评论

      本文标题:LeetCode 253 Meeting Rooms II

      本文链接:https://www.haomeiwen.com/subject/nwwbzftx.html