LC.P1606[找到处理最多请求的服务器]

方法一:有序集合+优先队列

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
class Solution {
public List<Integer> busiestServers(int k, int[] arrival, int[] load) {
int n = arrival.length, max = 0;
int[] cnt = new int[k];
TreeSet<Integer> available = new TreeSet<>();
for (int i = 0; i < k; ++i) available.add(i);
PriorityQueue<int[]> q = new PriorityQueue<>((a, b) -> a[1] - b[1]);
for (int i = 0; i < n; ++i) {
int startTime = arrival[i], endTime = startTime + load[i];
while (!q.isEmpty() && q.peek()[1] <= startTime) available.add(q.poll()[0]);
if (available.isEmpty()) continue;
Integer p = available.ceiling(i % k);
if (p == null) p = available.first();
++cnt[p];
available.remove(p);
q.offer(new int[]{p, endTime});
max = Math.max(max, cnt[p]);
}
List<Integer> ans = new ArrayList<>();
for (int i = 0; i < k; ++i) {
if (cnt[i] == max) ans.add(i);
}
return ans;
}
}
  • 时间复杂度:$O((n + k)logk)$
  • 空间复杂度:$O(k)$