Skip to content

Commit 0d0be1c

Browse files
authored
Create 1834. Single-Threaded CPU
1 parent cbb423a commit 0d0be1c

File tree

1 file changed

+63
-0
lines changed

1 file changed

+63
-0
lines changed

1834. Single-Threaded CPU

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
class Solution {
2+
public int[] getOrder(int[][] tasks) {
3+
//How to store the tasks
4+
//Task(index, startTime, processingTime)
5+
//Sort : StartTime ==> processingTime
6+
7+
int n = tasks.length;
8+
Task[] t = new Task[n];
9+
for(int i = 0; i < n; i++) {
10+
t[i] = new Task(i, tasks[i][0], tasks[i][1]);
11+
}
12+
13+
Arrays.sort(t, (a,b) -> a.startTime == b.startTime ? a.processingTime- b.processingTime : a.startTime - b.startTime);
14+
15+
16+
//How to pick the task
17+
//Priority Queue
18+
//Sorting => ProcessingTime (asc) ==> index (asc)
19+
20+
PriorityQueue<Task> waitingTasks = new PriorityQueue<>((a,b) -> a.processingTime == b.processingTime ? a.index-b.index : a.processingTime - b.processingTime);
21+
22+
int[] result = new int[n];
23+
int index = 0, resIndex = 0;
24+
int endTime = 0;
25+
26+
while(index < n) {
27+
if(waitingTasks.size() > 0) {
28+
//Calculate new EndTime and process one task
29+
//Pick the next Task, calculte the new endTime, Fill the waitingTasks Queue
30+
Task currentTask = waitingTasks.remove();
31+
endTime = Math.max(currentTask.startTime, endTime) + currentTask.processingTime;
32+
result[resIndex++] = currentTask.index;
33+
34+
while(index < n && endTime >= t[index].startTime) {
35+
waitingTasks.add(t[index++]);
36+
}
37+
}
38+
else {
39+
//Add a task in waitingTasks List
40+
waitingTasks.add(t[index++]);
41+
}
42+
}
43+
44+
while(waitingTasks.size() > 0) {
45+
Task task = waitingTasks.remove();
46+
result[resIndex++] = task.index;
47+
}
48+
49+
return result;
50+
}
51+
52+
class Task {
53+
int index;
54+
int startTime;
55+
int processingTime;
56+
57+
Task(int index, int startTime, int processingTime) {
58+
this.index = index;
59+
this.startTime= startTime;
60+
this.processingTime = processingTime;
61+
}
62+
}
63+
}

0 commit comments

Comments
 (0)