: BST ๋ก ๊ตฌ์ฑ๋๋ค. ์๊ฐ๋ณต์ก๋๋ nlogn
end์๊ฐ์ผ๋ก ์ค๋ฆ์ฐจ์์ผ๋ก MinHeap์ ๊ตฌ์ฑํ๊ฒ ๋๋ฉด ์๋์ ๊ฐ๋ค.
package java_basic;
import java.util.Arrays;
import java.util.Comparator;
import java.util.PriorityQueue;
import java.util.Queue;
class Interval {
int start;
int end;
Interval() {start = 0; end = 0;}
Interval(int s, int e) {start = s; end = e;}
}
public class MeetingRoom2 {
public static void main(String[] args) {
Interval in1 = new Interval(5,10);
Interval in2 = new Interval(0,30);
Interval in3 = new Interval(15,25);
Interval[] intervals = {in1,in2,in3};
MeetingRoom2 MR2 = new MeetingRoom2();
/*int result = MR2.solve(intervals);
System.out.println("ํ์ํ ๋ฏธํ
๋ฃธ ๊ฐฏ์ :" + result);*/
System.out.println(MR2.solve(intervals));
}
public int solve(Interval[] intervals) {
if(intervals == null || intervals.length == 0) return 0;
//์๊ณ ๋ฆฌ์ฆ ๊ตฌํ.
//1. start time์ผ๋ก ์ ๋ ฌ. ๋ฐ์ intervals๊ฐ ๋ฐฐ์ด์ด๋๊น
Arrays.sort(intervals,(a,b)->(a.start-b.start));
//2. end time์ผ๋ก ์ ๋ ฌ, ์ฐ์ ์์ํ MinHeap.
Queue<Interval> minHeap = new PriorityQueue<Interval>(intervals.length,Comp);
minHeap.offer(intervals[0]);
for(int i=1; i <= intervals.length;i++) {
Interval interval = minHeap.poll();//else์ธ ๊ฒฝ์ฐ ๋๊ฐ๊ฐ ํ์ํ๋ฐ pollํ๋ฉด ์ด๋ปํจ.
if(interval.end <= intervals[i].start) {//ํ๋๋ก ํฉ์น๋ค!
interval.end = Math.max(interval.end, intervals[i].end);
} else {//๋ฏธํ
๋ฃธ ํ๋ ๋ ์์ฑ(ํ์ ๋
ธ๋ ํ๋ ์ถ๊ฐ)
minHeap.offer(intervals[i]);
}
minHeap.offer(interval);
}
return minHeap.size();
}
Comparator Comp = new Comparator<Interval>() {
public int compare(Interval a, Interval b) {
return a.end - b.end;
}
};
}