1
+ // Runtime: 421 ms (Top 69.74%) | Memory: 172.7 MB (Top 82.56%)
1
2
class Solution {
2
3
public int [] assignTasks (int [] servers , int [] tasks ) {
3
-
4
+
4
5
PriorityQueue <int []> availableServer = new PriorityQueue <int []>((a , b ) -> (a [1 ] != b [1 ] ? (a [1 ] - b [1 ]) : (a [0 ] - b [0 ])));
5
6
for (int i = 0 ; i < servers .length ; i ++){
6
7
availableServer .add (new int []{i , servers [i ]});
7
8
}
8
-
9
-
10
- //int[[] arr,
9
+
10
+ //int[[] arr,
11
11
//arr[0] - server index
12
12
//arr[1] - server weight
13
13
//arr[2] - free time
14
14
PriorityQueue <int []> processingServer = new PriorityQueue <int []>(
15
- (a , b ) ->
16
-
17
- (
18
- a [2 ] != b [2 ] ? a [2 ] - b [2 ] : // try to sort increasing order of free time
19
- a [1 ] != b [1 ] ? a [1 ] - b [1 ] : // try to sort increasing order of server weight
20
- a [0 ] - b [0 ] // sort increasing order of server index
15
+ (a , b ) ->
16
+
17
+ (
18
+ a [2 ] != b [2 ] ? a [2 ] - b [2 ] : // try to sort increasing order of free time
19
+ a [1 ] != b [1 ] ? a [1 ] - b [1 ] : // try to sort increasing order of server weight
20
+ a [0 ] - b [0 ] // sort increasing order of server index
21
21
)
22
22
);
23
-
24
-
23
+
25
24
int [] result = new int [tasks .length ];
26
-
25
+
27
26
for (int i = 0 ; i < tasks .length ; i ++){
28
-
27
+
29
28
while (!processingServer .isEmpty () && processingServer .peek ()[2 ] <= i ){
30
29
int serverIndex = processingServer .remove ()[0 ];
31
30
availableServer .add (new int []{serverIndex , servers [serverIndex ]});
32
31
}
33
-
34
-
32
+
35
33
int currentTaskTimeRequired = tasks [i ];
36
-
34
+
37
35
int [] server ;
38
-
36
+
39
37
//when current task will free the server done
40
38
int freeTime = currentTaskTimeRequired ;
41
-
39
+
42
40
if (!availableServer .isEmpty ()){
43
41
server = availableServer .remove ();
44
42
freeTime += i ;
@@ -47,18 +45,15 @@ public int[] assignTasks(int[] servers, int[] tasks) {
47
45
//append previous time
48
46
freeTime += server [2 ];
49
47
}
50
-
51
-
48
+
52
49
int serverIndex = server [0 ];
53
50
processingServer .add (new int []{serverIndex , servers [serverIndex ] ,freeTime });
54
-
55
-
51
+
56
52
//assign this server to current task
57
53
result [i ] = serverIndex ;
58
54
}
59
-
60
-
55
+
61
56
return result ;
62
-
57
+
63
58
}
64
- }
59
+ }
0 commit comments