Sunday, April 24, 2022

Leet Code 632. Smallest Range Covering Elements from K Lists

https://leetcode.com/problems/smallest-range-covering-elements-from-k-lists/

Example 1:

Input: nums = [[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].












package pep.Day67;

import java.util.List;
import java.util.PriorityQueue;
import java.util.Queue;

public class LeetCode_632_Smallest_Range_Covering_Elements_from_K_Lists {

public static class Pair implements Comparable<Pair> {
int r, c, val;

Pair(int r, int c, int val) {
this.r = r;
this.c = c;
this.val = val;
}

public int compareTo(Pair other) {
return this.val - other.val;
}


}

public static int[] smallestRange(List<List<Integer>> nums) {

Queue<Pair> pq = new PriorityQueue<>();
int n = nums.size(), max = Integer.MIN_VALUE, range = Integer.MAX_VALUE, firstNumber = -1, secondNumber = -1;

// sab list mese ek ek element queue me daal diya, also, max nikal liya
for (int i = 0; i < n; i++) {
pq.add(new Pair(i, 0, nums.get(i).get(0)));
max = Math.max(max, nums.get(i).get(0));
}

while (pq.size() == n) {
Pair rem = pq.remove();

// update range agr choti mile to
if (max - rem.val < range) {
range = max - rem.val;
firstNumber = rem.val;
secondNumber = max;
}

if (rem.c + 1 < nums.get(rem.r).size()) {
pq.add(new Pair(rem.r, rem.c + 1, nums.get(rem.r).get(rem.c + 1)));
max = Math.max(max, nums.get(rem.r).get(rem.c + 1));
}

}

return new int[]{firstNumber, secondNumber};

}
}

No comments:

Post a Comment

Diagonal Traversal

 eg.  1       2       3       4 5      6       7       8 9    10    11     12 13  14   15    16 Output: 1 6 11 16 2 7 12 3 8 4  Approach:...