力扣刷题
题目
23.合并K个升序链表
给你一个链表数组,每个链表都已经按升序排列。
请你将所有链表合并到一个升序链表中,返回合并后的链表。
示例 1:
输入:lists = [[1,4,5],[1,3,4],[2,6]]
输出:[1,1,2,3,4,4,5,6]
解释:链表数组如下:
[
1->4->5,
1->3->4,
2->6
]
将它们合并到一个有序链表中得到。
1->1->2->3->4->4->5->6
示例 2:
输入:lists = []
输出:[]
示例 3:
输入:lists = [[]]
输出:[]
提示:
k == lists.length
0 <= k <= 10^4
0 <= lists[i].length <= 500
-10^4 <= lists[i][j] <= 10^4
lists[i] 按 升序 排列
lists[i].length 的总和不超过 10^4
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/merge-k-sorted-lists
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
java解答
1.创建一新链表ans,用来保存合并后链表并与新链表进行合并
/**
* 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 merge2Lists(ListNode a, ListNode b) {
if (a == null) return b;
if (b == null) return a;
if (a == null && b == null) return null;
ListNode c = new ListNode(0);
ListNode head1 = a;
ListNode head2 = b;
ListNode head3 = c;
while (head1 != null && head2 != null) {
if (head1.val < head2.val) {
head3.next = new ListNode(head1.val);
head1 = head1.next;
head3 = head3.next;
} else {
head3.next = new ListNode(head2.val);
head2 = head2.next;
head3 = head3.next;
}
}
if (head1 != null) {
head3.next = head1;
}
if (head2 != null) {
head3.next = head2;
}
return c.next;
}
public ListNode mergeKLists(ListNode[] lists) {
ListNode ans = null;
for (int i = 0; i <= lists.length - 1; i++) {
ans = merge2Lists(ans, lists[i]);
}
return ans;
}
}
2.利用PriorityQueue
/**
* 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) {
ListNode dummy=new ListNode(0);
ListNode head=dummy;
PriorityQueue<ListNode> pq=new PriorityQueue<>(Comparator.comparingInt(o -> o.val));
for(ListNode l:lists){
if(l!=null) pq.add(l);
}
while(!pq.isEmpty()){
ListNode curr=pq.poll();
head.next=curr;
head=head.next;
if(curr.next!=null) pq.add(curr.next);
}
return dummy.next;
}
}