码迷,mamicode.com
首页 > 其他好文 > 详细

[LC] 23. Merge k Sorted Lists

时间:2020-01-01 11:48:12      阅读:88      评论:0      收藏:0      [点我收藏+]

标签:code   solution   class   sorted   init   des   space   one   ISE   

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

Solution 1:
Time: O(Nlgk)
Space: O(N)
 * 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;
        }
        ListNode dummy = new ListNode(-1);
        ListNode cur = dummy;
        PriorityQueue<ListNode> pq = new PriorityQueue<>(lists.length, (a, b) -> a.val - b.val);
        // need to check list null as well
        for(ListNode list: lists) {
            if (list != null) {
                pq.add(list);
            }
        }
        while(!pq.isEmpty()) {
            ListNode node = pq.poll();
            cur.next = node;
            cur = cur.next;
            if (node.next != null) {
                pq.add(node.next);
            }
        }
        return dummy.next;
    }
}

 

solution 2:

Time: O(Nlgk)
Space: O(N)
/**
 * 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;
        }
        ListNode res = sort(lists, 0, lists.length - 1);
        return res;
    }
    
    private ListNode sort(ListNode[] lists, int low, int high) {
        if (low >= high) {
            return lists[high];
        }
        int mid = low + (high - low) / 2;
        ListNode left = sort(lists, low, mid);
        ListNode right = sort(lists, mid + 1, high);
        return merge(left, right);
    }
    
    private ListNode merge(ListNode aNode, ListNode bNode) {
        if (aNode == null) {
            return bNode;
        }
        if (bNode == null) {
            return aNode;
        }
        if (aNode.val <= bNode.val) {
            aNode.next = merge(aNode.next, bNode);
            return aNode;
        } else {
            bNode.next = merge(aNode, bNode.next);
            return bNode;
        }
    }
}

[LC] 23. Merge k Sorted Lists

标签:code   solution   class   sorted   init   des   space   one   ISE   

原文地址:https://www.cnblogs.com/xuanlu/p/12128382.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!