File tree Expand file tree Collapse file tree 1 file changed +52
-0
lines changed
19 - Heap Data Structure Problems/12 - Merge K Sorted Arrays Expand file tree Collapse file tree 1 file changed +52
-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+
21+ class Solution
22+ {
23+ public:
24+ // Function to merge k sorted arrays.
25+ vector<int > mergeKArrays (vector<vector<int >> arr, int K)
26+ {
27+ priority_queue<Node*, vector<Node*>, compare> pq;
28+
29+ for (int i = 0 ; i < K; i++){
30+ Node* temp = new Node (arr[i][0 ], i, 0 );
31+ pq.push (temp);
32+ }
33+
34+ vector<int > answer;
35+
36+ while (pq.size () > 0 ){
37+ Node* temp = pq.top ();
38+ answer.push_back (temp -> data);
39+ pq.pop ();
40+
41+ int i = temp -> row;
42+ int j = temp -> col;
43+
44+ if (j+1 < arr[i].size ()){
45+ Node* next = new Node (arr[i][j+1 ], i, j+1 );
46+ pq.push (next);
47+ }
48+ }
49+
50+ return answer;
51+ }
52+ };
You can’t perform that action at this time.
0 commit comments