Leetcode 253: meeting room

Opium_Z發表於2019-03-10

Arrang classes, you’re gonna figure out the min classroom required.

input: [0, 30],[5, 10],[15, 20]
output: 2

Java:



/*
 * public class Interval {
	int start;
	int end;
	
	public Interval() {
		this.start = 0;
		this.end = 0;
	}
		
	public Interval(int s, int e) {
		this.start = s;
		this.end = e;
	}	
}
 */



class Solution {
	
	
	public static int minMeetingRooms(Interval[] intervals) {

		Arrays.sort(intervals, new Comparator<Interval>(){
			@Override
			public int compare(Interval i1, Interval i2) {
				return i1.start - i2.start;
			}
		});
		
		int room = 0;
		PriorityQueue<Interval> minHeap = new PriorityQueue<Interval>((Interval i1, Interval i2) -> i1.end - i2.end);
		for (Interval temp:intervals) {
			minHeap.offer(temp);
			if (temp.start < minHeap.peek().end) room++;
			else minHeap.poll();
		}
		return room;
	}
	
	
	public static void main(String[] args) {
		
		Interval[] intervals = {new Interval(0, 30), new Interval(5, 10), new Interval(15, 20)};	
		System.out.println(minMeetingRooms(intervals));	
		
	}  
	
}

另一個騷氣的方法,將class 開始的時間map成+1, 結束的時間map成-1; 最後遍歷,和最大的時候就是min room


class Solution {

	public static int minMeetingRooms(Interval[] intervals) {
	
		Arrays.sort(intervals, ((Interval i1, Interval i2) -> i2.end - i1.end));
		int[] map = new int[intervals[0].end+1];
		
		for (Interval temp:intervals) {
			map[temp.start]++;
			map[temp.end]--;
		}
		
		int sum = 0, max = 0;
		for (int i=0; i<map.length; i++) {
			
			sum += map[i];
			max = Math.max(sum, max);
			
		}
	
		return max;
		
	}
}


相關文章