|
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_23_ms_(97.67%)_Space_87.33_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])); |
19 | | - int l = 0; |
20 | | - 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); |
| 17 | + Arrays.sort(qarr, (a, b) -> a[1] - b[1]); |
| 18 | + int[] ans = new int[m]; |
| 19 | + int[] freq = new int[n + 1]; |
| 20 | + int l = 0, r = 0, noReq = n; |
| 21 | + for (int[] q : qarr) { |
| 22 | + int i = q[0], t = q[1]; |
| 23 | + while (r < len && logs[r][1] <= t) { |
| 24 | + if (freq[logs[r][0]]++ == 0) { |
| 25 | + noReq--; |
| 26 | + } |
| 27 | + r++; |
29 | 28 | } |
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); |
| 29 | + while (l < len && logs[l][1] < t - x) { |
| 30 | + if (freq[logs[l][0]]-- == 1) { |
| 31 | + noReq++; |
| 32 | + } |
33 | 33 | l++; |
34 | 34 | } |
35 | | - res[i] = n - servCount.size(); |
| 35 | + ans[i] = noReq; |
36 | 36 | } |
37 | | - return res; |
| 37 | + return ans; |
38 | 38 | } |
39 | 39 | } |
0 commit comments