接着上一篇https://blog.csdn.net/znzxc/article/details/86590154
上一篇是自实现堆排序,这一次用priority_queue实现
struct MinHeapNode
{
int val;
int i;
int j;
MinHeapNode(int a, int b, int c)
:val(a), i(b), j(c) {}
};
struct cmp
{
bool operator()(const MinHeapNode& m1, const MinHeapNode&m2) const
{
return m1.val > m2.val;
}
};
vector<int> mergeKarrays(vector<vector<int>> &nums)
{
vector<int> res;
priority_queue<MinHeapNode, vector<MinHeapNode>, cmp> pq;
for (int i = 0; i < nums.size(); i++)
pq.push(MinHeapNode(nums[i][0], i, 1));
while (!pq.empty())
{
MinHeapNode temp = pq.top();
pq.pop();
res.push_back(temp.val);
if (temp.j < nums[temp.i].size())
{
temp.val = nums[temp.i][temp.j];
temp.j++;
pq.push(temp);
}
}
return res;
}
int main()
{
vector<vector<int>> nums;
nums.push_back({ 1,3,6,9,10 });
nums.push_back({ -1,2,4,5,12 });
nums.push_back({ -4,1,7,15,22 });
nums.push_back({ -8,0,3,4,15 });
vector<int> res = mergeKarrays(nums);
for (auto i : res)
cout << i << " ";
getchar();
return 0;
}