| 1 | class Solution { |
| 2 | public int[] smallestRange(List<List<Integer>> nums) { |
| 3 | //min heap |
| 4 | // [element, listIndex, elementIndex] |
| 5 | PriorityQueue<int[]> pq = new PriorityQueue<>(new Comparator<int[]>(){ |
| 6 | public int compare(int a[], int b[]){ |
| 7 | return a[0] - b[0]; //inc |
| 8 | } |
| 9 | }); |
| 10 | int k = nums.size(); |
| 11 | int max = Integer.MIN_VALUE; |
| 12 | |
| 13 | for (int i = 0; i < k; i++) { |
| 14 | int minVal = nums.get(i).get(0); |
| 15 | pq.offer(new int[]{minVal, i, 0}); |
| 16 | max = Math.max(max, minVal); |
| 17 | } |
| 18 | int[] minRange = {0, Integer.MAX_VALUE}; |
| 19 | while (true) { |
| 20 | int top[] = pq.poll(); |
| 21 | int minElement = top[0], listIndex = top[1], elementIndex = top[2]; |
| 22 | if (max - minElement < minRange[1] - minRange[0]) { |
| 23 | minRange[0] = minElement; |
| 24 | minRange[1] = max; |
| 25 | } |
| 26 | if (elementIndex == nums.get(listIndex).size() - 1) break; |
| 27 | int next = nums.get(listIndex).get(elementIndex + 1); |
| 28 | max = Math.max(max, next); |
| 29 | pq.offer(new int[]{next, listIndex, elementIndex + 1}); |
| 30 | } |
| 31 | return minRange; |
| 32 | } |
| 33 | } |
nothing calls this directly
no outgoing calls
no test coverage detected