合并K个有序数组(假设每个数组长度相等)

本文介绍了一种使用最小堆来合并多个已排序数组的方法。通过定义结构体存储数值及索引信息,并实现调整最小堆的函数,最终完成数组合并。代码示例展示了如何创建最小堆并逐步合并数组。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

直接上代码,看注释

#include <iostream>
using namespace std;

struct HeapNode {
	int val;//num value
	int i;//array index
	int j;//num index
};

//length of each array
static const int numLen = 3;

//adjust minheap
void MinHeapFixDown(HeapNode data[], int i, const int len) {
	HeapNode tmp = data[i];
	int j = 2*i+1;
	while (j < len) {
		if (j+1 < len && data[j+1].val < data[j].val)
			++j;
		if (data[j].val >= tmp.val)
			break;
		data[i] = data[j];
		i = j;
		j = 2*i+1;
	}
	data[i] = tmp;
}

//Create Min Heap
void MakeMinHeap(HeapNode data[], const int len) {
	for (int i = len/2-1; i >= 0; --i)
		MinHeapFixDown(data, i, len);
}

//Merge Array
void MergeArray(int nums[][numLen], const int k, int res[]) {
	//temp array used to store nodes
	HeapNode tmp[k];
	//initialize the tmp by the first element of each array
	for (int i = 0; i < k; ++i){
		tmp[i].val = nums[i][0];
		tmp[i].i = i;
		tmp[i].j = 0;
	}
	//Create the heap
	MakeMinHeap(tmp, k);
	int count = 0; //count the number of arrays been merged
	int index = 0; //result array index
	//until all the arrays been merged
	while (count != k) {
		//the first element of the array is the minimum
		res[index++] = tmp[0].val;
		//if not walk to the end of one array
		if (tmp[0].j != numLen-1) {
			//update the the node into the next node in the ith array
			tmp[0].j = tmp[0].j+1;
			tmp[0].val = nums[tmp[0].i][tmp[0].j];
			//adjust the heap
			MinHeapFixDown(tmp, 0, k-count);
		}
		//if walk to the end of one array
		else {
			//count plus one
			++count;
			//assign the first node with the last node
			tmp[0] = tmp[k-count];
			//adjust the heap
			//Note::len is k-count
			MinHeapFixDown(tmp, 0, k-count);
		}
	}
}

int main() {
	const int row = 6;
	int nums[row][numLen] = {{22,112,210},{2,5,12},{6,9,13},{7,8,10},{3,11,28},{13,14,15}};
	int res[row*numLen];
	MergeArray(nums, row, res);
	for (int i = 0 ; i < row*numLen; ++i)
		cout<<res[i]<<endl;
	return 0;
}


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值