1. 程式人生 > >LeetCode題解-23 合並K個排序鏈表 Hard

LeetCode題解-23 合並K個排序鏈表 Hard

tco lis 排序 tro return ini pre 答案 ...

合並 k 個排序鏈表,返回合並後的排序鏈表。請分析和描述算法的復雜度。

示例:

輸入:
[
  1->4->5,
  1->3->4,
  2->6
]
輸出: 1->1->2->3->4->4->5->6

答案:

/**
 * 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;
        return helper(lists, 0 , lists.length-1);
        
    }
    
    ListNode helper(ListNode[] lists, int l , int r){
        //[l...r];
        if(l == r)
            return lists[l];
        int mid = l+(r-l)/2;
        ListNode left = helper(lists,l,mid);
        ListNode right = helper(lists,mid+1,r);
        return merge(left,right);
        
    }
    
    ListNode merge(ListNode left, ListNode right){
        ListNode dummyHead = new ListNode(0),cur;
        cur = dummyHead;
        
        while(left!=null || right!=null){
            if(left != null && right !=null){
                if(left.val<right.val){
                cur.next=left;
                cur=left;
                    left = left.next;
                    }
                else{
                    cur.next=right;
                    cur=right;
                    right=right.next;
                }
            }else if(left==null){
                    cur.next=right;
                    cur=right;
                    right=right.next;
                
            }else if(right==null){
                cur.next=left;
                cur=left;
                    left = left.next;
                
            }
        }
        return dummyHead.next;
    }
}

LeetCode題解-23 合並K個排序鏈表 Hard