EPI (Heap) Merge Multiple sorted arrays.

#include <vector>
#include <iostream>
#include <queue>
using namespace std;

/*
  Write a program that takes an input a set of sorted sequences and compute the union
  of these sequences as a sorted sequence.
  For example:
  [3, 5, 7], [0, 6, 8], [0, 6, 28], then the output is [0, 0, 3, 5, 6, 6, 7, 28]
*/
/*
  This problem can further be divided into two. 
  1: There are only two sorted sets.
  2: The number of input sets are more than two.
*/
// Time complexity: O(N), Space O(N)
vector<int> mergeTwoSets(vector<int>& set_1, vector<int>& set_2) {
  int m = set_1.size();
  if(m == 0) return set_2;
  int n = set_2.size();
  if(n == 0) return set_1;
  vector<int> res;
  int i = 0, j = 0;
  while(i < m && j < n) {
    if(set_1[i] <= set_2[j]) {
      res.push_back(set_1[i++]);
    } else {
      res.push_back(set_2[j++]);
    }
  }
  while(i < m) {
    res.push_back(set_1[i++]);
  }
  while(j < n) {
    res.push_back(set_2[j++]);
  }
  return res;
}
void printVector(vector<int>& res) {
  for(int i = 0; i < res.size(); ++i) {
    cout << res[i] << endl;
  }
}

// Identical with merging multiple sorted lists. Time complexity: NlgK (K is the number of input size). Space lgK
vector<int> mergeMultiSets(const vector< vector<int> >& sets) {
  struct IteratorStartAndEnd {
    bool operator < (const IteratorStartAndEnd& that) const {
      return *start > *that.start;
    }
    vector<int>::const_iterator start;
    vector<int>::const_iterator end;
  };
  priority_queue< IteratorStartAndEnd, vector<IteratorStartAndEnd> > minHeap;
  for(const vector<int>& sorted_array : sets) {
    if(!sorted_array.empty())
    minHeap.push(IteratorStartAndEnd{sorted_array.cbegin(), sorted_array.cend()});
  }

  vector<int> res;
  while(!minHeap.empty()) {
    auto smallest_array = minHeap.top();
    minHeap.pop();
    if(smallest_array.start  != smallest_array.end) {
      res.push_back(*smallest_array.start);
      minHeap.push(IteratorStartAndEnd{next(smallest_array.start), smallest_array.end});
    }
  }
  return res;
}
int main(void) {
  vector<int> set_1{0, 15};
  vector<int> set_2{2, 3, 10, 12};
  vector<int> set_3{2, 3, 9, 14};
//  vector<int> res = mergeTwoSets(set_1, set_2);
  //printVector(res);
  vector< vector<int> > multisets;
  multisets.push_back(set_1);
  multisets.push_back(set_2);
  multisets.push_back(set_3);
  vector<int> res_1 = mergeMultiSets(multisets);
  printVector(res_1);
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值