|
1 | 1 | package g2701_2800.s2747_count_zero_request_servers;
|
2 | 2 |
|
3 | 3 | // #Medium #Array #Hash_Table #Sorting #Sliding_Window
|
4 |
| -// #2023_09_24_Time_43_ms_(76.92%)_Space_85.7_MB_(63.85%) |
| 4 | +// #2025_02_23_Time_22_ms_(100.00%)_Space_87.21_MB_(63.95%) |
5 | 5 |
|
6 | 6 | import java.util.Arrays;
|
7 |
| -import java.util.Comparator; |
8 |
| -import java.util.HashMap; |
9 | 7 |
|
10 | 8 | public class Solution {
|
11 |
| - public int[] countServers(int n, int[][] logs, int x, int[] qs) { |
12 |
| - int m = qs.length; |
13 |
| - var valIdx = new int[m][2]; |
| 9 | + public int[] countServers(int n, int[][] logs, int x, int[] queries) { |
| 10 | + Arrays.sort(logs, (a, b) -> a[1] - b[1]); |
| 11 | + int m = queries.length; |
| 12 | + int len = logs.length; |
| 13 | + int[][] qarr = new int[m][]; |
14 | 14 | for (int i = 0; i < m; i++) {
|
15 |
| - valIdx[i] = new int[] {qs[i], i}; |
| 15 | + qarr[i] = new int[] {i, queries[i]}; |
16 | 16 | }
|
17 |
| - Arrays.sort(valIdx, Comparator.comparingInt(a -> a[0])); |
18 |
| - Arrays.sort(logs, Comparator.comparingInt(a -> a[1])); |
| 17 | + Arrays.sort(qarr, (a, b) -> a[1] - b[1]); |
| 18 | + int[] ans = new int[m]; |
| 19 | + int[] freq = new int[n + 1]; |
19 | 20 | int l = 0;
|
20 | 21 | int r = 0;
|
21 |
| - var res = new int[m]; |
22 |
| - var servCount = new HashMap<Integer, Integer>(); |
23 |
| - for (var q : valIdx) { |
24 |
| - int rVal = q[0]; |
25 |
| - int lVal = q[0] - x; |
26 |
| - int i = q[1]; |
27 |
| - while (r < logs.length && logs[r][1] <= rVal) { |
28 |
| - servCount.merge(logs[r++][0], 1, Integer::sum); |
| 22 | + int noReq = n; |
| 23 | + for (int[] q : qarr) { |
| 24 | + int i = q[0]; |
| 25 | + int t = q[1]; |
| 26 | + while (r < len && logs[r][1] <= t) { |
| 27 | + if (freq[logs[r][0]]++ == 0) { |
| 28 | + noReq--; |
| 29 | + } |
| 30 | + r++; |
29 | 31 | }
|
30 |
| - while (l < r && logs[l][1] < lVal) { |
31 |
| - servCount.compute(logs[l][0], (k, v) -> v - 1); |
32 |
| - servCount.remove(logs[l][0], 0); |
| 32 | + while (l < len && logs[l][1] < t - x) { |
| 33 | + if (freq[logs[l][0]]-- == 1) { |
| 34 | + noReq++; |
| 35 | + } |
33 | 36 | l++;
|
34 | 37 | }
|
35 |
| - res[i] = n - servCount.size(); |
| 38 | + ans[i] = noReq; |
36 | 39 | }
|
37 |
| - return res; |
| 40 | + return ans; |
38 | 41 | }
|
39 | 42 | }
|
0 commit comments