我正在尝试解决一个具有以下描述的问题:
一次只有一个人可以在舞台上表演,并且每个参与者的到达时间和持续时间以阵列的形式给出。找到可以参加的最大参加人数。
示例:
到达时间:[1、3、3、5、7]
持续时间:[2,2,1,2,1]
答案应为4,即1-3; 3-5或3-4; 5-7; 7-8
因此,我可以找到每个参与者的退出时间。当时间重叠时,如何找到可能的最大事件数。
我尝试过的代码是:
int count = 1;
for(int i=0;i<entry.size()-1;i++) {
if(entry.get(i) < exit.get(i+1)) {
count++;
}
}
return count;
我使用到达时间+持续时间找到了退出列表,但是很多测试都失败了。上面的示例通过了,但是在某些情况下,重叠时间可能会有更多的参与者。
我不知道如何进行。
答案 0 :(得分:5)
更新了答案,并添加了新的测试用例,这清楚地表明,如果表演者具有相同的到达时间,则可以对其进行重新排序。 第二次更新:对每个表演者的结束时间(到达时间+持续时间)进行排序。 保留当前表演者的endTime。只有表演者才可以表演,在当前表演者结束后才能到达。
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class LifeGig {
public static class Performer {
int arrival, duration;
Performer(int arrival, int duration) {
this.arrival = arrival;
this.duration = duration;
}
@Override
public String toString() {
return "Performer [arrival=" + arrival + ", duration=" + duration + "]";
}
}
public List<Performer> program(int[] entry,int[] duration)
{
List<Performer> performers=new ArrayList<>();
for(int i=0;i<entry.length;i++)
{
performers.add(new Performer(entry[i],duration[i]));
}
Collections.sort(performers, new Comparator<Performer>() {
@Override
public int compare(Performer p1, Performer p2) {
return Integer.compare(p1.arrival+p1.duration, p2.arrival+p2.duration);
}
});
List<Performer> festival=new ArrayList<>();
System.out.println(performers);
int currentTime = 1;
for (Performer p:performers) {
if (p.arrival >= currentTime) {
currentTime = p.arrival+p.duration;
festival.add(p);
}
}
return festival;
}
public static void test1()
{
int[] entry = new int[] {1,3,3,5,7};
int[] duration = new int[] {2,2,1,2,1};
List<Performer> festival=new LifeGig().program(entry,duration);
System.out.println("Count (Expected=4): " + festival.size());
System.out.println("lineup:"+festival);
}
public static void test2()
{
int[] entry = new int[] {1, 1, 1, 1, 4};
int[] duration = new int[] {10, 3, 6, 4, 2};
List<Performer> festival=new LifeGig().program(entry,duration);
System.out.println("Count (Expected=2): " + festival.size());
System.out.println("lineup:"+festival);
}
public static void test3()
{
int[] entry = new int[] {1,2,3,4};
int[] duration = new int[] {10, 1,1,1,};
List<Performer> festival=new LifeGig().program(entry,duration);
System.out.println("Count (Expected=3): " + festival.size());
System.out.println("lineup:"+festival);
}
public static void main(String[] args) {
test1();
test2();
test3();
}
}