美文网首页LeetCode solutions
23. Merge k Sorted Lists

23. Merge k Sorted Lists

作者: 番茄晓蛋 | 来源:发表于2016-12-24 13:39 被阅读2次

My Submissions

Total Accepted: 121007
Total Submissions: 469882
Difficulty: Hard
Contributors: Admin

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

Hide Company Tags
LinkedIn Google Uber Airbnb Facebook Twitter Amazon Microsoft
Hide Tags
Divide and Conquer Linked List Heap
Hide Similar Problems
(E) Merge Two Sorted Lists (M) Ugly Number II

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ListNode mergeKLists(ListNode[] lists) {
      return partition(lists, 0, lists.length - 1);
    }
    
    public ListNode partition(ListNode[] lists, int s, int e) {
        if (s == e) return lists[s];
        
        if (s < e) {
            int m = (s + e) / 2;
            ListNode l1 = partition(lists, s, m);
            ListNode l2 = partition(lists, m + 1, e);
            return merge(l1, l2);
        } else {
            return null;
        }
    }
    
    public ListNode merge(ListNode l1, ListNode l2) {
        ListNode res = new ListNode(0);
        ListNode p = res;
        
        if (l1 == null) return l2;
        if (l2 == null) return l1;
        
        while (l1 != null && l2 != null) {
            if (l1.val < l2.val) {
                p.next = new ListNode(l1.val);
                l1 = l1.next;
            } else {
                p.next = new ListNode(l2.val);
                l2 = l2.next;
            }
            p = p.next;
        }
        
        if (l1 != null) p.next = l1;
        if (l2 != null) p.next = l2;
        return res.next;
    }
}

相关文章

网友评论

    本文标题: 23. Merge k Sorted Lists

    本文链接:https://www.haomeiwen.com/subject/olwlvttx.html