Leetcode: Merge k Sorted Lists

来源:互联网 发布:淘宝优惠券怎么设置 编辑:程序博客网 时间:2024/06/15 18:45

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

Divide and conquer: Divide the list into two parts, and use recursion to divide the two parts and merge. Time complexity O(nklogk), n is the length of the longest linked list. Space complexity is the heap size O(logk) 

/** * Definition for singly-linked list. * public class ListNode { *     int val; *     ListNode next; *     ListNode(int x) { *         val = x; *         next = null; *     } * } */public class Solution {    public ListNode mergeKLists(List<ListNode> lists) {        if (lists == null || lists.size() == 0) {            return null;        }                if (lists.size() == 1) {            return lists.get(0);        }                ListNode p1 = mergeKLists(lists.subList(0, lists.size() / 2));        ListNode p2 = mergeKLists(lists.subList(lists.size() / 2, lists.size()));        return merge2Lists(p1, p2);    }            private ListNode merge2Lists(ListNode p1, ListNode p2) {        if (p1 == null) return p2;        ListNode dummy = new ListNode(0);        dummy.next = p1;                ListNode h1 = dummy;        ListNode h2 = h1.next;        while (p2 != null) {            if (h2 == null) {                h1.next = p2;                break;            }            if (p2.val < h2.val) {                ListNode temp = p2.next;                h1.next = p2;                p2.next = h2;                p2 = temp;            }             h1 = h1.next;            h2 = h1.next;        }                return dummy.next;    }}


0 0
原创粉丝点击