title: leetcode-23-合并k个有序链表
date: 2019-09-07 10:56:17
categories:
- leetcode
tags: - leetcode
合并k个有序链表
-
合并 k 个排序链表,返回合并后的排序链表。请分析和描述算法的复杂度。
示例:
输入:
[
1->4->5,
1->3->4,
2->6
]
输出: 1->1->2->3->4->4->5->6来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/merge-k-sorted-lists
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 -
解法一:分治,利用上一题的合并两个有序链表的方法,利用分治达到目的,不过左边和右边有三种情况:
- left=right-1:这时候right–,同时令left=0
- left=right-2 这时候right还是–,同时令left=0;
- 不是上面两个条件,证明不是上面的内容,即没有到链表遍历完成
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ class Solution { public ListNode mergeKLists(ListNode[] lists) { if(lists.length==0) return null; int left = 0; int right = lists.length-1; while (left<right){ lists[left] = mergeTwoLists(lists[left],lists[right]); if (left==right-1){ left = 0; right--; }else if(left==right-2){ left = 0; right--; }else { left++; right--; } } return lists[0]; } public ListNode mergeTwoLists(ListNode l1, ListNode l2) { ListNode l3 = new ListNode(0); ListNode l4 = l3; while(l1!=null&&l2!=null) { if(l1.val>l2.val) { l3.next = l2; l2 = l2.next; }else{ l3.next = l1; l1 = l1.next; } l3 = l3.next; } if(l1==null) { l3.next = l2; }else{ l3.next = l1; } return l4.next; } }
-
解法二:贪心算法:使用优先队列:还可以使用堆来进行,优先队列确实我没有想到的方法,因为优先队列可以自己建立比较方法,同时优先队列是可以优化成为堆的,使用优先队列就相当于这道题开挂了
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ class Solution { public ListNode mergeKLists(ListNode[] lists) { int len = lists.length; if (len == 0) { return null; } PriorityQueue<ListNode> priorityQueue = new PriorityQueue<>(len, Comparator.comparingInt(a -> a.val)); ListNode dummyNode = new ListNode(-1); ListNode curNode = dummyNode; for (ListNode list : lists) { if (list != null) { // 这一步很关键,不能也没有必要将空对象添加到优先队列中 priorityQueue.add(list); } } while (!priorityQueue.isEmpty()) { // 优先队列非空才能出队 ListNode node = priorityQueue.poll(); // 当前节点的 next 指针指向出队元素 curNode.next = node; // 当前指针向前移动一个元素,指向了刚刚出队的那个元素 curNode = curNode.next; if (curNode.next != null) { // 只有非空节点才能加入到优先队列中 priorityQueue.add(curNode.next); } } return dummyNode.next; } }