|
| 1 | +package K_Way_Merge; |
| 2 | + |
| 3 | +// Problem Statement: Kth Smallest Number in M Sorted Lists (medium) |
| 4 | +// LeetCode Question: |
| 5 | + |
| 6 | +import java.util.List; |
| 7 | +import java.util.PriorityQueue; |
| 8 | + |
| 9 | +public class Problem_2_Kth_Smallest_Number_In_M_Sorted_List { |
| 10 | + |
| 11 | + class Node { |
| 12 | + int elementIndex; |
| 13 | + int arrayIndex; |
| 14 | + |
| 15 | + Node(int elementIndex, int arrayIndex) { |
| 16 | + this.elementIndex = elementIndex; |
| 17 | + this.arrayIndex = arrayIndex; |
| 18 | + } |
| 19 | + } |
| 20 | + |
| 21 | + public int findKthSmallest(List<List<Integer>> lists, int k) { |
| 22 | + PriorityQueue<Node> minHeap = new PriorityQueue<>( |
| 23 | + (n1, n2) -> lists.get(n1.arrayIndex).get(n1.elementIndex) |
| 24 | + - lists.get(n2.arrayIndex).get(n2.elementIndex)); |
| 25 | + |
| 26 | + // put the 1st element of each list in the min heap |
| 27 | + for (int i = 0; i < lists.size(); i++) { |
| 28 | + if (!lists.get(i).isEmpty()) { |
| 29 | + minHeap.add(new Node(0, i)); |
| 30 | + } |
| 31 | + } |
| 32 | + |
| 33 | + // take the smallest (top) element from the min heap, if the running count is equal |
| 34 | + // to k, return the number; if the list of the top element has more elements, add the |
| 35 | + // next element to the heap |
| 36 | + int numberCount = 0, result = 0; |
| 37 | + while (!minHeap.isEmpty()) { |
| 38 | + Node node = minHeap.poll(); |
| 39 | + result = lists.get(node.arrayIndex).get(node.elementIndex); |
| 40 | + if (++numberCount == k) { |
| 41 | + break; |
| 42 | + } |
| 43 | + node.elementIndex++; |
| 44 | + if (node.elementIndex < lists.get(node.arrayIndex).size()) { |
| 45 | + minHeap.add(node); |
| 46 | + } |
| 47 | + } |
| 48 | + return result; |
| 49 | + } |
| 50 | + |
| 51 | +} |
0 commit comments