FB面经 Prepare: Task Schedule

时间:2024-10-04 16:34:32
tasks has cooldown time, give an input task id array, output finish time
input: AABCA
A--ABCA
output:7
 package fb;

 import java.util.*;

 public class Scheduler {

     public int task(int[] tasks, int cooldown) {
int time = 0;
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>(); StringBuilder output = new StringBuilder(); for (int i=0; i<tasks.length; i++) {
if (!map.containsKey(tasks[i]) || time>=map.get(tasks[i])) {
map.put(tasks[i], time+cooldown);
time++; output.append(tasks[i]);
}
else { // time < map.get(tasks[i])
for (int k=time; k<map.get(tasks[i]); k++) {
output.append("-");
} time = map.get(tasks[i]);
map.put(tasks[i], time+cooldown);
time++; output.append(tasks[i]);
}
}
return time;
} public static void main(String[] args) {
Scheduler sc = new Scheduler();
//int res = sc.task(new int[]{1,1,2,3,1}, 3);
int res = sc.task(new int[]{1,2,1,2,3}, 3);
//String output = sc.task(new int[]{1,2,2,1,3}, 3);
System.out.println(res);
//System.out.println(output);
}
}