-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSmallest Range Covering Elements from K Lists.cpp
More file actions
56 lines (52 loc) · 1.4 KB
/
Copy pathSmallest Range Covering Elements from K Lists.cpp
File metadata and controls
56 lines (52 loc) · 1.4 KB
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
struct Node{
int data;
int row;
int col;
Node(int d, int r, int c) : data{d}, row{r}, col{c} {}
};
class myComp{
public:
int operator()(const Node& a, const Node& b){
return a.data > b.data;
}
};
class Solution {
public:
vector<int> smallestRange(vector<vector<int>>& arr) {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
priority_queue<Node, vector<Node>, myComp> pq;
vector<int> res;
int max_ele = 0, min_ele;
int dis, s, e;
int k = arr.size();
for(int i = 0; i < k; i++){
pq.push(Node(arr[i][0], i, 0));
max_ele = max(max_ele, arr[i][0]);
}
min_ele = pq.top().data;
dis = max_ele - min_ele;
s = min_ele;
e = max_ele;
while(1){
Node temp = pq.top();
pq.pop();
int x = temp.row, y = temp.col, n = arr[x].size();
if(y + 1 < n)
pq.push(Node(arr[x][y + 1], x, y + 1));
if(y + 1 < n && max_ele < arr[x][y + 1])
max_ele = arr[x][y + 1];
if(y + 1 == n)
break;
min_ele = pq.top().data;
if(dis > max_ele - min_ele){
dis = max_ele - min_ele;
s = min_ele;
e = max_ele;
}
}
res.push_back(s);
res.push_back(e);
return res;
}
};