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
+ }