forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.java
39 lines (39 loc) · 1.15 KB
/
Solution.java
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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
class Solution {
public int[] smallestRange(List<List<Integer>> nums) {
int n = 0;
for (var v : nums) {
n += v.size();
}
int[][] t = new int[n][2];
int k = nums.size();
for (int i = 0, j = 0; i < k; ++i) {
for (int x : nums.get(i)) {
t[j++] = new int[] {x, i};
}
}
Arrays.sort(t, (a, b) -> a[0] - b[0]);
int j = 0;
Map<Integer, Integer> cnt = new HashMap<>();
int[] ans = new int[] {-1000000, 1000000};
for (int[] e : t) {
int b = e[0];
int v = e[1];
cnt.put(v, cnt.getOrDefault(v, 0) + 1);
while (cnt.size() == k) {
int a = t[j][0];
int w = t[j][1];
int x = b - a - (ans[1] - ans[0]);
if (x < 0 || (x == 0 && a < ans[0])) {
ans[0] = a;
ans[1] = b;
}
cnt.put(w, cnt.get(w) - 1);
if (cnt.get(w) == 0) {
cnt.remove(w);
}
++j;
}
}
return ans;
}
}