23. Merge k Sorted Lists

使用归并

/**
 * 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;
        if(lists.length==1)return lists[0];
        return merge(lists,0,lists.length-1);
    }
    public ListNode merge(ListNode[] lists,int low,int high){
        if(high==low){
            return lists[high];          
        }
        if(high-low==1)
            return merge2Lists(lists[low],lists[high]);
        if(high<low)
            return null;
        return merge2Lists(merge(lists,low,(low+high)/2),merge(lists,(low+high)/2+1,high));
    }
    public ListNode merge2Lists(ListNode x,ListNode y){
        if(x==null)return y;
        if(y==null)return x;
        
        ListNode cur = null,head = null;
        ListNode p = x, q = y;
        if(p.val<=q.val){
            cur = p;
            p = p.next;
        }else{
            cur = q;
            q = q.next;
        }
        head = cur;
        while(p!=null&&q!=null){
            if(p.val<=q.val){
                cur.next = p;
                p = p.next;
            }else{
                cur.next = q;
                q = q.next;
            }
            cur = cur.next;
        }
        if(p==null)cur.next=q;
        if(q==null)cur.next=p;
        return head;
    }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容