LinkedList - 23. Merge k Sorted Lists

时间:2022-07-25
本文章向大家介绍LinkedList - 23. Merge k Sorted Lists,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

23. Merge k Sorted Lists

Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.

Example:

Input: [   1->4->5,   1->3->4,   2->6 ] Output: 1->1->2->3->4->4->5->6

思路:

合并k个有序链表,采用分治的思想,时间复杂度O(nlogk)

代码:

/**

 * 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 == null || lists.length == 0)
            return null;
        return helper(lists, 0, lists.length - 1);
    }
    
    private ListNode helper(ListNode[] lists, int start, int end) {
        if (start == end) return lists[start];
        
        int mid = (end - start) / 2 + start;
        ListNode first = helper(lists, start, mid);
        ListNode second = helper(lists, mid + 1, end);
        
        ListNode head = new ListNode(-1);
        ListNode cur = head;
        while (first != null && second != null) {
            if (first.val < second.val) {
                cur.next = first;
                first = first.next;
            } else {
                cur.next = second;
                second = second.next;
            }
            cur = cur.next;
        }
        if (first == null) 
            cur.next = second;
        if (second == null)
            cur.next = first;
        
        return head.next;
    }
}