活动安排问题

问题描述

一些项目要占用一个会议室宣讲,会议室不能同时容纳两个项目的宣讲。

每一个项目开始的时间和结束的时间(给你一个数组, 里面是一个个具体的项目),要求会议室进行的宣讲的场次最多。
返回这个最多的宣讲场次。

分析

如果以开始时间早来贪心

反例:

1
2
3
a-----------------------------------------------------

b---- c--- d-------- e---------- f -----

如果以持续时间短来贪心

反例:

1
2
3
a----------------------------          b---------------------------

c---------------

代码解决

用最早结束时间做贪心。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
import java.util.Arrays;
import java.util.Comparator;

public class BestArrange {
public static class Node{
public int start;
public int end;
public Node(int start,int end){
this.start = start;
this.end = end;
}
}

public static int bestArray(Node[]node){
if(node==null || node.length==0){
return 0;
}
Arrays.sort(node,new endComparator()); // 哪场会议结束时间早就排在前面
int res = 0;
int cur=node[0].start;
for (int i = 0; i < node.length; i++) {
if(cur<=node[i].start){
res++;
cur = node[i].end;// 记录下一场能开始的时间
System.out.println("做第"+(i+1) +"个项目。开始时间:"+node[i].start+",结束时间: "+node[i].end);
}
}
return res;
}

public static class endComparator implements Comparator<Node>{
@Override
public int compare(Node o1, Node o2) {
return o1.end-o2.end;
}
}

public static void main(String[] args) {
Node node[] = new Node[10];
node[0] = new Node(1, 3);
node[1] = new Node(0, 7);
node[2] = new Node(15, 20);
node[3] = new Node(3, 4);
node[4] = new Node(3, 8);
node[5] = new Node(5, 10);
node[6] = new Node(6, 12);
node[7] = new Node(4, 14);
node[8] = new Node(10, 15);
node[9] = new Node(15, 18);
System.out.println("总共做了"+bestArray(node)+"个项目");//5
}
}

测试输出

> >