Skip to content

Commit c86f479

Browse files
committed
Improved task 2747
1 parent 09f4055 commit c86f479

File tree

1 file changed

+24
-24
lines changed
  • src/main/java/g2701_2800/s2747_count_zero_request_servers

1 file changed

+24
-24
lines changed
Lines changed: 24 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -1,39 +1,39 @@
11
package g2701_2800.s2747_count_zero_request_servers;
22

33
// #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%)
55

66
import java.util.Arrays;
7-
import java.util.Comparator;
8-
import java.util.HashMap;
97

108
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][];
1414
for (int i = 0; i < m; i++) {
15-
valIdx[i] = new int[] {qs[i], i};
15+
qarr[i] = new int[] {i, queries[i]};
1616
}
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++;
2928
}
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+
}
3333
l++;
3434
}
35-
res[i] = n - servCount.size();
35+
ans[i] = noReq;
3636
}
37-
return res;
37+
return ans;
3838
}
3939
}

0 commit comments

Comments
 (0)