数组合并
假设有 n 个长度为 k 的已排好序(升序)的数组,请设计数据结构和算法,将这 n 个数组合并到一个数组,且各元素按升序排列。即实现函数:
void merge_arrays(const int* arr, int n, int k, int* output);
其中 arr 为按行优先保存的 n 个长度都为 k 的数组,output 为合并后的按升序排列的数组,大小为 n×k。
时间要求(评分规则),当 n > k 时:
- 满分:时间复杂度不超过 O(n×k×log(n))
- 75分:时间复杂度不超过 O(n×k×log(n)×k)
- 59分:其它,如:时间复杂度为 O(n2×k2) 时。
答案
#include<stdio.h>
#include<stdlib.h>
#define R1 (row / 2)
#define R2 (row - row / 2)
void merge(int* f1, int* f2, int* output, int num1, int num2) {//queue the two Sequence tables in f,and store the put the result in output
int i1 = 0, i2 = 0;
while (i1 < num1 && i2 < num2) {
if (f1[i1] <= f2[i2]) {
output[i1+i2] = f1[i1];
i1++;
}
else {
output[i1 + i2] = f2[i2];
i2++;
}
}
while (i1 < num1) {
output[i1+i2] = f1[i1];
i1++;
}
while (i2 < num2) {
output[i1+i2] = f2[i2];
i2++;
}
}
void merge_arrays(const int* arr, int row, int col, int* output) {
int* f1 = (int*)malloc(R1 * col * sizeof(int));
int* f2 = (int*)malloc(R2 * col * sizeof(int));
const int* SA = &arr[0], * SB = &arr[row / 2 * col];
if (SA == SB) {
for (int i = 0; i < row * col; i++) {
output[i] = SA[i];
}
return;
}
merge_arrays(SA, R1, col, f1);
merge_arrays(SB, R2, col, f2);
merge(f1,f2, output, R1 * col, R2*col);
}