[AlgoExpert] Merge Sorted Arrays

Merge Sorted Arrays

  • Time : O(nlogk)
  • Space : O(k)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
using namespace std;

vector<int> mergeSortedArrays(vector<vector<int>> arrays) {
priority_queue<array<int,3>, vector<array<int,3>>, greater<array<int,3>>> pq;
vector<int> res;
for(int i = 0; i < arrays.size(); i++) {
if(arrays[i].empty()) continue;
pq.push({arrays[i][0], i, 1});
}
while(!pq.empty()) {
auto [v, id, idx] = pq.top(); pq.pop();
res.push_back(v);
if(arrays[id].size() != idx)
pq.push({arrays[id][idx], id, idx + 1});
}
return res;
}

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/09/PS/AlgoExpert/merge-sorted-arrays/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.