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
| class Solution { public int[] assignTasks(final int[] servers, final int[] tasks) { if (tasks == null || tasks.length == 0 || servers == null || servers.length == 0) return new int[0];
PriorityQueue<int[]> serverInUser = new PriorityQueue<>((a, b) -> { int av = a[1] - b[1]; if (av != 0) return av; int p = servers[a[0]] - servers[b[0]]; return p == 0 ? a[0] - b[0] : p; });
PriorityQueue<int[]> freeServer = new PriorityQueue<>((a, b) -> { int p = servers[a[0]] - servers[b[0]]; return p == 0 ? a[0] - b[0] : p; });
for (int i = 0; i < servers.length; i++) { freeServer.add(new int[]{i, 0}); }
int[] result = new int[tasks.length];
for (int i = 0; i < tasks.length; i++) { int len = tasks[i];
while (!serverInUser.isEmpty() && serverInUser.peek()[1] <= i) { freeServer.add(serverInUser.poll()); } int[] s = null; if (!freeServer.isEmpty()) { s = freeServer.poll(); s[1] = i + len; } else { s = serverInUser.poll(); s[1] += len; } serverInUser.add(s); result[i] = s[0]; } return result; } }
|