-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathMergeKSortedArray.java
More file actions
55 lines (42 loc) · 1.41 KB
/
Copy pathMergeKSortedArray.java
File metadata and controls
55 lines (42 loc) · 1.41 KB
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
55
package Array;
import java.util.PriorityQueue;
/** Priority Queue is Heap in Java.
* Created by Prashant on 7/2/16.
* http://www.geeksforgeeks.org/merge-k-sorted-arrays/
* also do: http://www.programcreek.com/2013/02/leetcode-merge-k-sorted-lists-java/
* http://www.interviewsansar.com/2015/05/16/what-is-time-complexity-for-offer-poll-and-peek-methods-in-priority-queue/
*/
class ArrayContainer implements Comparable<ArrayContainer>{
int[] a;
int index;
public ArrayContainer(int[] a, int index) {
this.a = a;
this.index = index;
}
@Override
public int compareTo(ArrayContainer o) {
return this.a[this.index] - o.a[o.index];
}
}
public class MergeKSortedArray {
public static void main(String[] args) {
int arr[][] = { {1, 3, 5, 7},
{2, 4, 6, 8},
{0, 9, 10, 11}} ;
PriorityQueue<ArrayContainer> q = new PriorityQueue<ArrayContainer>();
int total = 0;
for(int i=0;i<arr.length;i++) {
q.add(new ArrayContainer(arr[i], 0));
total+=arr[i].length;
}
int[] res = new int[total];
while(!q.isEmpty()) {
ArrayContainer ac = q.poll();
System.out.print(ac.a[ac.index] + ",");
if(ac.index < ac.a.length-1) {
q.add(new ArrayContainer(ac.a, ac.index+1));
}
}
System.out.print(" ");
}
}