-
Notifications
You must be signed in to change notification settings - Fork 0
/
23.合并k个升序链表.java
46 lines (41 loc) · 1.06 KB
/
23.合并k个升序链表.java
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
import java.util.PriorityQueue;
/*
* @lc app=leetcode.cn id=23 lang=java
*
* [23] 合并K个升序链表
*/
// @lc code=start
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode mergeKLists(ListNode[] lists) {
if (lists.length == 0)
return null;
PriorityQueue<ListNode> pq = new PriorityQueue<>(lists.length, (a, b) -> a.val - b.val);
for (int i = 0; i < lists.length; i++) {
if (lists[i] != null) {
pq.add(lists[i]);
}
}
ListNode vNode = new ListNode(-1);
ListNode cur = vNode;
while (pq.peek() != null) {
ListNode min = pq.poll();
cur.next = min;
cur = cur.next;
if (min.next != null) {
pq.add(min.next);
}
}
return vNode.next;
}
}
// @lc code=end