-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathleet20.java
More file actions
38 lines (30 loc) · 1.28 KB
/
leet20.java
File metadata and controls
38 lines (30 loc) · 1.28 KB
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
class Solution {
public int[] smallestRange(List<List<Integer>> nums) {
PriorityQueue<int[]> minHeap = new PriorityQueue<>((a, b) -> a[0] - b[0]);
int curMax = Integer.MIN_VALUE;
for (int i = 0; i < nums.size(); i++) {
minHeap.offer(new int[]{nums.get(i).get(0), i, 0});
curMax = Math.max(curMax, nums.get(i).get(0));
}
int[] smallRange = new int[]{0, Integer.MAX_VALUE};
while (true) {
int[] curr = minHeap.poll();
int curMin = curr[0], listIdx = curr[1], elemIdx = curr[2];
if ((curMax - curMin < smallRange[1] - smallRange[0]) ||
(curMax - curMin == smallRange[1] - smallRange[0] && curMin < smallRange[0])) {
smallRange[0] = curMin;
smallRange[1] = curMax;
}
// Move to the next element in the same list
if (elemIdx + 1 < nums.get(listIdx).size()) {
int nextVal = nums.get(listIdx).get(elemIdx + 1);
minHeap.offer(new int[]{nextVal, listIdx, elemIdx + 1});
curMax = Math.max(curMax, nextVal);
} else {
// If any list is exhausted, stop
break;
}
}
return smallRange;
}
}