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(1) to delete the minimum element.

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

 

转载于:https://www.cnblogs.com/beiyeqingteng/p/6251070.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值