Skip to content

Commit 533cbb7

Browse files
authored
Merge pull request #2497 from leahjia/1882-process-tasks-using-servers
Create 1882-process-tasks-using-servers.java
2 parents 2a2fb2f + d9127ec commit 533cbb7

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
class Solution {
2+
public int[] assignTasks(int[] servers, int[] tasks) {
3+
int[] res = new int[tasks.length];
4+
5+
// [weight, index]
6+
Queue<int[]> available = new PriorityQueue<>((a, b) -> a[0] == b[0] ? a[1] - b[1] : a[0] - b[0]);
7+
for (int i = 0; i < servers.length; i++)
8+
available.add(new int[] { servers[i], i });
9+
10+
int time = 0;
11+
int nextTask = 0;
12+
// [weight, index, done time]
13+
Queue<int[]> unavail = new PriorityQueue<>((a, b) -> a[2] - b[2]);
14+
while (nextTask < tasks.length) {
15+
// release available servers
16+
while (!unavail.isEmpty() && unavail.peek()[2] <= time) {
17+
int[] curr = unavail.poll();
18+
available.add(new int[] { curr[0], curr[1] });
19+
}
20+
21+
// assign task(s)
22+
while (!available.isEmpty() && nextTask < time && nextTask != tasks.length) {
23+
int[] curr = available.poll();
24+
unavail.add(new int[] { curr[0], curr[1], time + tasks[nextTask] });
25+
res[nextTask++] = curr[1];
26+
}
27+
28+
// advance time
29+
if (available.isEmpty())
30+
time = unavail.peek()[2];
31+
else
32+
time++;
33+
}
34+
return res;
35+
}
36+
}

0 commit comments

Comments
 (0)