#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); }
时间: 2024-10-14 10:35:50