原题链接在这里:https://leetcode.com/problems/smallest-range-covering-elements-from-k-lists/
题目:
You have k
lists of sorted integers in ascending order. Find the smallest range that includes at least one number from each of the k
lists.
We define the range [a,b] is smaller than range [c,d] if b-a < d-c
or a < c
if b-a == d-c
.
Example 1:
Input: [[4,10,15,24,26], [0,9,12,20], [5,18,22,30]] Output: [20,24] Explanation: List 1: [4, 10, 15, 24,26], 24 is in range [20,24]. List 2: [0, 9, 12, 20], 20 is in range [20,24]. List 3: [5, 18, 22, 30], 22 is in range [20,24].
Note:
- The given list may contain duplicates, so ascending order means >= here.
- 1 <=
k
<= 3500 - -105 <=
value of elements
<= 105.
题解:
Consider this question this way, if there are 2 rows, how to do it. We need 2 pointers and move the smaller pointer every time to update smallest range.
Now we have > 2 rows, we need a PriorityQueue to get the smallest value.
And we also need to know which row and index of that row, thus we use an array to track all of this.
Time Complexity: O(n * logk). k = nums.size(). n is length of longest list.
Space: O(k).
AC Java:
1 class Solution { 2 public int[] smallestRange(List<List<Integer>> nums) { 3 if(nums == null || nums.size() == 0){ 4 return new int[0]; 5 } 6 7 int [] res = new int[2]; 8 PriorityQueue<int []> minHeap = new PriorityQueue<>((a, b) -> a[0] - b[0]); 9 int max = Integer.MIN_VALUE; 10 int minLen = Integer.MAX_VALUE; 11 int n = nums.size(); 12 for(int i = 0; i < n; i++){ 13 int num = nums.get(i).get(0); 14 minHeap.add(new int[]{num, i, 0}); 15 max = Math.max(max, num); 16 } 17 18 while(minHeap.size() == n){ 19 int [] cur = minHeap.poll(); 20 if(max - cur[0] < minLen){ 21 minLen = max - cur[0]; 22 res[0] = cur[0]; 23 res[1] = max; 24 } 25 26 if(cur[2] < nums.get(cur[1]).size() - 1){ 27 int num = nums.get(cur[1]).get(cur[2] + 1); 28 minHeap.add(new int[]{num, cur[1], cur[2] + 1}); 29 max = Math.max(max, num); 30 } 31 } 32 33 return res; 34 } 35 }