-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy path1834. Single-Threaded CPU.java
64 lines (64 loc) · 2.16 KB
/
1834. Single-Threaded CPU.java
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
53
54
55
56
57
58
59
60
61
62
63
64
class Solution {
public int[] getOrder(int[][] tasks) {
int n=tasks.length;
int[] ans=new int[n];
Task[] extTasks=new Task[n]; //extTasks : exist Tasks
for(int i=0;i<n;i++){
Task nt=new Task(tasks[i][0],tasks[i][1],i); //nt:new task
extTasks[i]=nt;
}
Arrays.sort(extTasks,new StartTime());
PriorityQueue<Task> pq=new PriorityQueue<>(new Duration());
int ai=0; //ai : answer index [will help to fill answer array]
int ti=0; //ti : task index [ iterate over existing tasks,will help to know tasks pending]
int currentTime=0;
while(ai<n){
while(ti<n && extTasks[ti].startTime<=currentTime){
pq.add(extTasks[ti++]);
}
if(pq.size()==0){
currentTime=extTasks[ti].startTime;
continue;
}
Task bestFit=pq.remove();
ans[ai++]=bestFit.index;
currentTime+=bestFit.processTime;
}
return ans;
}
// will use this to sort on the basis of start time
public class StartTime implements Comparator<Task>{
@Override
public int compare(Task one,Task two){
return one.startTime-two.startTime;
}
}
//will use this in priorityQueue
public class Duration implements Comparator<Task>{
@Override
public int compare(Task one,Task two){
if(one.processTime==two.processTime) return one.index-two.index;
return one.processTime-two.processTime;
}
}
public class Task{
int startTime;
int processTime;
int index;
Task(int startTime,int processTime,int index){
this.startTime=startTime;
this.processTime=processTime;
this.index=index;
}
}
}