1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
|
import java.util.ArrayList;
import java.util.List;
import java.util.PriorityQueue;
public class App {
public static void main(String[] args) {
/* n 个有序的数组 输入
输出一个有序地数组*/
int[] arr1 = new int[]{0,1,3,5,7,9};
int[] arr2 = new int[]{2,4,6,8,10, 100};
ArrayList<int[]> input = new ArrayList<>();
input.add(arr1);
input.add(arr2);
for (int i : sortArr(input)) {
System.out.printf(" " + i);
}
}
public static int[] sortArr(List<int[]> arrList) {
List<Integer> list = new ArrayList<>();
PriorityQueue<CustomedArr> heap = new PriorityQueue<>((a, b) -> a.arr[a.index] - b.arr[b.index]);
for (int[] ints : arrList) {
heap.add(new CustomedArr(ints, 0));
}
while (!heap.isEmpty()) {
CustomedArr poll = heap.poll();
list.add(poll.arr[poll.index]);
poll.index++;
if (poll.index < poll.arr.length) {
heap.add(poll);
}
}
//理论上, foreach 循环的效率会高于 stream 的多次调用, 这里为了易读性选择了 stream
int[] res = list.stream().mapToInt(Integer::intValue).toArray();
return res;
}
static class CustomedArr{
int[] arr;
int index;
public CustomedArr(int[] arr, int index) {
this.arr = arr;
this.index = index;
}
}
}
|