|
| 1 | +package com.fishercoder.solutions; |
| 2 | + |
| 3 | +import java.util.List; |
| 4 | +import java.util.PriorityQueue; |
| 5 | + |
| 6 | +/** |
| 7 | + * 632. Smallest Range |
| 8 | + * |
| 9 | + * You have k lists of sorted integers in ascending order. |
| 10 | + * Find the smallest range that includes at least one number from each of the k lists. |
| 11 | +
|
| 12 | + 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. |
| 13 | +
|
| 14 | + Example 1: |
| 15 | + Input:[[4,10,15,24,26], [0,9,12,20], [5,18,22,30]] |
| 16 | + Output: [20,24] |
| 17 | + Explanation: |
| 18 | + List 1: [4, 10, 15, 24,26], 24 is in range [20,24]. |
| 19 | + List 2: [0, 9, 12, 20], 20 is in range [20,24]. |
| 20 | + List 3: [5, 18, 22, 30], 22 is in range [20,24]. |
| 21 | +
|
| 22 | + Note: |
| 23 | + The given list may contain duplicates, so ascending order means >= here. |
| 24 | + 1 <= k <= 3500 |
| 25 | + -105 <= value of elements <= 105. |
| 26 | + For Java users, please note that the input type has been changed to List<List<Integer>>. |
| 27 | + And after you reset the code template, you'll see this point. |
| 28 | +
|
| 29 | + */ |
| 30 | +public class _632 { |
| 31 | + /**reference: https://discuss.leetcode.com/topic/94445/java-code-using-priorityqueue-similar-to-merge-k-array/2*/ |
| 32 | + public int[] smallestRange(List<List<Integer>> nums) { |
| 33 | + PriorityQueue<int[]> minHeap = new PriorityQueue<>(nums.size(), (a, b) -> a[0] - b[0]); |
| 34 | + /**int[] array consists of three numbers: value; which list in nums; index of value in this list*/ |
| 35 | + |
| 36 | + int max = nums.get(0).get(0); |
| 37 | + for (int i = 0; i < nums.size(); i++) { |
| 38 | + minHeap.offer(new int[]{nums.get(i).get(0), i, 0}); |
| 39 | + max = Math.max(max, nums.get(i).get(0)); |
| 40 | + } |
| 41 | + int minRange = Integer.MAX_VALUE; |
| 42 | + int start = -1; |
| 43 | + while (minHeap.size() == nums.size()) { |
| 44 | + int[] curr = minHeap.poll(); |
| 45 | + if (max - curr[0] < minRange) { |
| 46 | + minRange = max - curr[0]; |
| 47 | + start = curr[0]; |
| 48 | + } |
| 49 | + if (curr[2]+1 < nums.get(curr[1]).size()) { |
| 50 | + curr[0] = nums.get(curr[1]).get(curr[2]+1); |
| 51 | + curr[2]++; |
| 52 | + minHeap.offer(curr); |
| 53 | + max = Math.max(max, curr[0]); |
| 54 | + } |
| 55 | + } |
| 56 | + return new int[]{start, start + minRange}; |
| 57 | + } |
| 58 | +} |
0 commit comments