-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathSmallestRangeFromKArrays.java
70 lines (61 loc) · 1.7 KB
/
SmallestRangeFromKArrays.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
/*https://practice.geeksforgeeks.org/problems/find-smallest-range-containing-elements-from-k-lists/1*/
class Element implements Comparable<Element>
{
int array;
int index;
int element;
Element(int a, int i, int e)
{
array = a;
index = i;
element = e;
}
public int compareTo(Element e)
{
return this.element - e.element;
}
}
class smallestRangeFromKLists
{
static int[] findSmallestRange(int[][] arr,int n,int k)
{
int[] result = new int[2];
//create a min heap
PriorityQueue<Element> minHeap = new PriorityQueue<Element>();
int minRange = Integer.MAX_VALUE;
int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;
//add all the first elements and find the maximum too
for (int i = 0; i < arr.length; ++i)
{
minHeap.add(new Element(i,0,arr[i][0]));
max = Math.max(max,arr[i][0]);
}
//till no array is exhausted
while (minHeap.size() == k)
{
//set the minimum element
Element minElem = minHeap.poll();
min = minElem.element;
//update the range and result
if (minRange > max-min+1)
{
minRange = max-min+1;
result[0] = min;
result[1] = max;
}
//update the heap and max as well
if (minElem.index+1 < n)
{
Element newElem = new Element(minElem.array,minElem.index+1,arr[minElem.array][minElem.index+1]);
minHeap.add(newElem);
if (newElem.element > max)
max = newElem.element;
}
//when one array is exhausted, break
else
break;
}
return result;
}
}