fork(1) download
  1. #include<iostream>
  2. #include<queue>
  3. #include<vector>
  4. using namespace std;
  5.  
  6. typedef pair<int, pair<int,int> > node;
  7. vector<int> mergeKSortedArray(vector<vector<int> > arr){
  8. vector<int>result;
  9. priority_queue<node, vector<node>, greater<node> > pq;//min priority queue
  10. //insert 0th element of each arr to pq
  11. for(int i=0;i<arr.size();i++){
  12. pq.push({arr[i][0],{i,0}});//we need to store 3 things - val of ele, index of arr, index of ele
  13. }
  14. //remove the ele one by one from min heap and add it to the result vector
  15. while(!pq.empty()){
  16. node current = pq.top();
  17. pq.pop();
  18. int element = current.first;
  19. int x = current.second.first;//row in which element is present
  20. int y = current.second.second;//col in which element is present
  21.  
  22. result.push_back(element);
  23. //you need to push in pq the next element of current x,y+1
  24. if(y+1<arr.size()){
  25. pq.push({arr[x][y+1],{x,y+1}});
  26. }
  27. }
  28. return result;
  29. }
  30. int main(){
  31. vector<vector<int> >arr{{2,6,12,15},
  32. {1,3,14,20},
  33. {3,5,8,10}};
  34.  
  35. vector<int>output = mergeKSortedArray(arr);
  36. for(auto x:output){
  37. cout<<x<<" ";
  38. }
  39.  
  40.  
  41.  
  42. return 0;}
  43.  
Success #stdin #stdout 0s 4228KB
stdin
Standard input is empty
stdout
1 2 3 3 5 6 8 12 14