题目 一些项目要占用一个会议室宣讲,会议室不能同时容纳两个项目的宣讲。 给你每一个项目开始的时间和结束的时间(给你一个数组,里面是一个个具体的项目),你来安排宣讲的日程,要求会议室进行的宣讲的场次最多。返回这个最多的宣讲场次。
思路 建立小根堆,将所有项目按结束时间end排序。从第一个项目开始遍历,假设第一个项目要进行宣讲,那么就看看第二项目的开始时间 是不是在第一个项目的结束时间 之后,如果是,那么第二个项目可以进行宣讲,否则跳过第二个项目。
package algorithm.section7;
import java.util.*;
public class BestArrange {
public static class Time{
public int start;
public int end;
public Time(int start, int end) {
this.start = start;
this.end = end;
}
}
public static class EndComparator implements Comparator<Time> {
@Override
public int compare(Time time1, Time time2) {
return time1.end - time2.end;
}
}
public static Queue<Time> bestArrange(Time[] times) {
if (times.length == 0) return null;
Queue<Time> res = new LinkedList<>();
int num = 0;
PriorityQueue<Time> queue = new PriorityQueue<>(new EndComparator());
for (int i = 0; i < times.length; i++) {
Queue<Time> r = new LinkedList<>();
int end = -1;
for (int j = i; j < times.length; j++){
queue.offer(times[j]);
}
while (!queue.isEmpty()) {
if (queue.peek().start >= end) {
r.add(queue.peek());
end = queue.peek().end;
}
queue.poll();
}
if (r.size() > num) {
num = r.size();
res = r;
}
}
return res;
}
public static Queue<Time> bestArrange1(Time[] times) {
if (times.length == 0) return null;
int p = 0;
int num = 0;
Arrays.sort(times, new EndComparator());
Queue<Time> res = new LinkedList<>();
for (int i = 0; i < times.length; i++) {
int end = -1;
Queue<Time> f = new LinkedList<>();
for (int j = i; j < times.length; j++) {
if (times[j].start >= end) {
f.offer(times[j]);
end = times[j].end;
}
}
if (f.size() > num) {
num = f.size();
res = f;
}
}
return res;
}
public static void main(String[] args) {
Time[] times = new Time[5];
times[0] = new Time(0, 2);
times[1] = new Time(3, 4);
times[2] = new Time(1, 3);
times[3] = new Time(4, 6);
times[4] = new Time(5, 6);
Queue<Time> res1 = bestArrange(times);
while (!res1.isEmpty()) System.out.print(res1.peek().start + ":" + res1.poll().end + " ");
System.out.println();
Queue<Time> res2 = bestArrange1(times);
while (!res2.isEmpty()) System.out.print(res2.peek().start + ":" + res2.poll().end + " ");
System.out.println();
Time[] times1 = new Time[6];
times1[0] = new Time(0, 3);
times1[1] = new Time(3, 5);
times1[2] = new Time(0, 1);
times1[3] = new Time(1, 3);
times1[4] = new Time(3, 5);
times1[5] = new Time(5, 6);
Queue<Time> res3 = bestArrange(times1);
while (!res3.isEmpty()) System.out.print(res3.peek().start + ":" + res3.poll().end + " ");
System.out.println();
Queue<Time> res4 = bestArrange1(times1);
while (!res4.isEmpty()) System.out.print(res4.peek().start + ":" + res4.poll().end + " ");
}
}