Skip to content

Commit 17b2eed

Browse files
authored
Create main.cpp
1 parent 6635757 commit 17b2eed

File tree

1 file changed

+65
-0
lines changed
  • 19 - Heap Data Structure Problems/15 - Smallest Range Covering Element from K Lists

1 file changed

+65
-0
lines changed
Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
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+
vector<int> smallestRange(vector<vector<int>>& nums) {
23+
int k = nums.size();
24+
25+
priority_queue<Node*, vector<Node*>, compare> pq;
26+
27+
int mini = INT_MAX;
28+
int maxi = INT_MIN;
29+
30+
for(int i = 0; i < k; i++){
31+
int element = nums[i][0];
32+
33+
maxi = max(maxi, element);
34+
mini = min(mini, element);
35+
36+
pq.push(new Node(element, i, 0));
37+
}
38+
39+
int start = mini;
40+
int end = maxi;
41+
42+
while(!pq.empty()){
43+
Node* temp = pq.top();
44+
pq.pop();
45+
46+
mini = temp -> data;
47+
48+
if(maxi - mini < end - start){
49+
start = mini;
50+
end = maxi;
51+
}
52+
53+
if(temp -> col + 1 < nums[temp -> row].size()){
54+
int nextElement = nums[temp -> row][temp -> col + 1];
55+
56+
maxi = max(nextElement, maxi);
57+
pq.push(new Node(nextElement, temp -> row, temp -> col + 1));
58+
}else{
59+
break;
60+
}
61+
}
62+
63+
return {start, end};
64+
}
65+
};

0 commit comments

Comments
 (0)