-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmerge_k_sorted_array.cpp
More file actions
58 lines (46 loc) · 1.4 KB
/
Copy pathmerge_k_sorted_array.cpp
File metadata and controls
58 lines (46 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
57
58
class Solution {
public:
/**
* @param arrays k sorted integer arrays
* @return a sorted array
*/
class Element {
public:
int val;
int row;
int col;
Element(int a, int b, int c) {
this->val = a;
this->row = b;
this->col = c;
}
};
struct comparator {
bool operator() (const Element &a, const Element &b) {
return a.val > b.val;
}
};
vector<int> mergekSortedArrays(vector<vector<int>>& arrays) {
// Write your code here
int k = arrays.size();
vector<int> result;
priority_queue<Element, vector<Element>, comparator> min_heap;
vector<int> len;
for (int i = 0; i < k; i++) {
len.push_back(arrays[i].size());
if (arrays[i].size() > 0) {
min_heap.push(Element(arrays[i][0], i, 0));
}
}
while (!min_heap.empty()) {
result.push_back(min_heap.top().val);
int row = min_heap.top().row;
int col = min_heap.top().col;
min_heap.pop();
if(col + 1 < len[row]) {
min_heap.push(Element(arrays[row][col + 1], row, col + 1));
}
}
return result;
}
};