File tree Expand file tree Collapse file tree 1 file changed +62
-0
lines changed
19 - Heap Data Structure Problems/14 - Smallest Range in K Lists Expand file tree Collapse file tree 1 file changed +62
-0
lines changed Original file line number Diff line number Diff line change 1+ class Node {
2+ public:
3+ int data;
4+ int row;
5+ int col;
6+
7+ Node (int data, int row, int col){
8+ this -> data = data;
9+ this -> row = row;
10+ this -> col = col;
11+ }
12+ };
13+
14+ class compare {
15+ public:
16+ bool operator ()(Node* a, Node* b){
17+ return a -> data > b -> data;
18+ }
19+ };
20+ class Solution {
21+ public:
22+ pair<int ,int > findSmallestRange (int arr[][N], int n, int k)
23+ {
24+ int mini = INT_MAX;
25+ int maxi = INT_MIN;
26+
27+ priority_queue<Node*, vector<Node*>, compare> minHeap;
28+
29+ for (int i = 0 ; i < k; i++){
30+ int element = arr[i][0 ];
31+
32+ mini = min (mini, element);
33+ maxi = max (maxi, element);
34+
35+ minHeap.push (new Node (element, i, 0 ));
36+ }
37+
38+
39+ int start = mini, end = maxi;
40+
41+ while (!minHeap.empty ()){
42+ Node* temp = minHeap.top ();
43+ minHeap.pop ();
44+
45+ mini = temp -> data;
46+
47+ if (maxi - mini < end - start){
48+ start = mini;
49+ end = maxi;
50+ }
51+
52+ if (temp -> col + 1 < n){
53+ maxi = max (maxi, arr[temp->row ][temp->col + 1 ]);
54+ minHeap.push (new Node (arr[temp->row ][temp->col + 1 ], temp -> row, temp -> col + 1 ));
55+ }else break ;
56+
57+ }
58+
59+ return {start, end};
60+
61+ }
62+ };
You can’t perform that action at this time.
0 commit comments