Skip to content

Commit d9127ec

Browse files
authored
Create 1882-process-tasks-using-servers.java
1 parent db55cd2 commit d9127ec

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)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy