Merge K Sorted Arrays

This problem can be solved by using a heap. The time is O(nlog(n)).

Given m arrays, the minimum elements of all arrays can form a heap. It takes O(log(m)) to insert an element to the heap and it takes O(log(m)) to delete the minimum element.

 1 class Record {
 2     int row;
 3     int col;
 4     int val;
 5 
 6     public Record(int row, int col, int val) {
 7         this.row = row;
 8         this.col = col;
 9         this.val = val;
10     }
11 }
12 
13 public class Solution {
14     public List<Integer> mergekSortedArrays(int[][] arrays) {
15         PriorityQueue<Record> minHeap = new PriorityQueue<>((x, y) -> x.val - y.val);
16         for (int i = 0; i < arrays.length; i++) {
17             if (arrays[i].length != 0) {
18                 minHeap.offer(new Record(i, 0, arrays[i][0]));
19             }
20         }
21 
22         List<Integer> result = new ArrayList<>();
23         while (!minHeap.isEmpty()) {
24             Record record = minHeap.poll();
25             result.add(record.val);
26             if (record.col + 1 < arrays[record.row].length) {
27                 minHeap.offer(new Record(record.row, record.col + 1, arrays[record.row][record.col + 1]));
28             }
29         }
30         return result;
31     }
32 }

 

posted @ 2017-01-05 08:52  北叶青藤  阅读(474)  评论(0编辑  收藏  举报