# 算法题：合并N个长度为L的有序数组为一个有序数组（JAVA实现）

import java.util.Arrays;
class Solution {
public static int[] MergeArrays(int[][] array) {
int N = array.length, L;
if (N == 0)
return new int[0];
else {
L = array[0].length;
for (int i = 1; i < N; i++)
if (L != array[i].length)
return new int[0];
}
int[] result = new int[N * L];
for (int i = 0; i < N; i++)
for (int j = 0; j < L; j++)
result[i * L + j] = array[i][j];
Arrays.sort(result);
return result;
}
}

import java.util.PriorityQueue;
import java.util.Arrays;
import java.util.Comparator;

public class SortedArraysMerge {
static class Node {
int value;
int idx;

public Node(int value, int idx) {
this.value = value;
this.idx = idx;
}
}

public static int[] MergeArrays(int[][] arr) {
int N = arr.length, L;
if (N == 0)//此时传入数组为空
return new int[0];
else {//判断数组是否符合规范
L = arr[0].length;
for (int i = 1; i < N; i++)
if (arr[i].length != L)
return new int[0]; //此时数组不规范
}
int[] result = new int[N * L];
int[] index = new int[N];
Arrays.fill(index, 0, N, 0);
PriorityQueue<Node> queue = new PriorityQueue<Node>(new Comparator<Node>() {
@Override
public int compare(Node n1, Node n2) {
if (n1.value < n2.value)
return -1;
else if (n1.value > n2.value)
return 1;
else
return 0;
}
});
for (int i = 0; i < N; i++) {
Node node = new Node(arr[i][index[i]++], i);
queue.offer(node);
}
System.out.println("" + queue.size());
int idx = 0;
while (idx < N * L) {
Node minNode = queue.poll();
result[idx++] = minNode.value;
if (index[minNode.idx] < L) {
queue.offer(new Node(arr[minNode.idx][index[minNode.idx]], minNode.idx));
index[minNode.idx]++;
}
}
return result;
}
}

posted @ 2018-03-21 19:00  郭耀华  阅读(4039)  评论(0编辑  收藏