|
28 | 28 |
|
29 | 29 | */ |
30 | 30 | public class _632 { |
31 | | - /** |
32 | | - * reference: https://discuss.leetcode.com/topic/94445/java-code-using-priorityqueue-similar-to-merge-k-array/2 |
33 | | - */ |
34 | | - public int[] smallestRange(List<List<Integer>> nums) { |
35 | | - PriorityQueue<int[]> minHeap = new PriorityQueue<>(nums.size(), (a, b) -> a[0] - b[0]); |
36 | | - /**int[] array consists of three numbers: value; which list in nums; index of value in this list*/ |
| 31 | + public static class Solution1 { |
| 32 | + /** |
| 33 | + * reference: https://discuss.leetcode.com/topic/94445/java-code-using-priorityqueue-similar-to-merge-k-array/2 |
| 34 | + */ |
| 35 | + public int[] smallestRange(List<List<Integer>> nums) { |
| 36 | + PriorityQueue<int[]> minHeap = new PriorityQueue<>(nums.size(), (a, b) -> a[0] - b[0]); |
| 37 | + /**int[] array consists of three numbers: value; which list in nums; index of value in this list*/ |
37 | 38 |
|
38 | | - int max = nums.get(0).get(0); |
39 | | - for (int i = 0; i < nums.size(); i++) { |
40 | | - minHeap.offer(new int[]{nums.get(i).get(0), i, 0}); |
41 | | - max = Math.max(max, nums.get(i).get(0)); |
42 | | - } |
43 | | - int minRange = Integer.MAX_VALUE; |
44 | | - int start = -1; |
45 | | - while (minHeap.size() == nums.size()) { |
46 | | - int[] curr = minHeap.poll(); |
47 | | - if (max - curr[0] < minRange) { |
48 | | - minRange = max - curr[0]; |
49 | | - start = curr[0]; |
| 39 | + int max = nums.get(0).get(0); |
| 40 | + for (int i = 0; i < nums.size(); i++) { |
| 41 | + minHeap.offer(new int[]{nums.get(i).get(0), i, 0}); |
| 42 | + max = Math.max(max, nums.get(i).get(0)); |
50 | 43 | } |
51 | | - if (curr[2] + 1 < nums.get(curr[1]).size()) { |
52 | | - curr[0] = nums.get(curr[1]).get(curr[2] + 1); |
53 | | - curr[2]++; |
54 | | - minHeap.offer(curr); |
55 | | - max = Math.max(max, curr[0]); |
| 44 | + int minRange = Integer.MAX_VALUE; |
| 45 | + int start = -1; |
| 46 | + while (minHeap.size() == nums.size()) { |
| 47 | + int[] curr = minHeap.poll(); |
| 48 | + if (max - curr[0] < minRange) { |
| 49 | + minRange = max - curr[0]; |
| 50 | + start = curr[0]; |
| 51 | + } |
| 52 | + if (curr[2] + 1 < nums.get(curr[1]).size()) { |
| 53 | + curr[0] = nums.get(curr[1]).get(curr[2] + 1); |
| 54 | + curr[2]++; |
| 55 | + minHeap.offer(curr); |
| 56 | + max = Math.max(max, curr[0]); |
| 57 | + } |
56 | 58 | } |
| 59 | + return new int[]{start, start + minRange}; |
57 | 60 | } |
58 | | - return new int[]{start, start + minRange}; |
59 | 61 | } |
60 | 62 | } |
0 commit comments