Leetcode23. Merge k Sorted Lists

先是暴力解法,一遍一遍遍历找到最小节点加入ans,如下,但是超时了 Time Limit Exceeded

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode mergeKLists(ListNode[] lists) {
        ListNode p = new ListNode(0);
        ListNode ans = p;
        ListNode minNode = lists[0];
        boolean isEnd = false;
        while(!isEnd) {
            isEnd = true;
            for(int i=0;i<lists.length;i++) {
                if(lists[i]==null) {
                    continue;
                }
                isEnd=false;
                if(minNode.val>lists[i].val) {
                    minNode=lists[i];
                    lists[i]=lists[i].next;
                }
            }
            if(!isEnd) {
                p.next = minNode;
                p=p.next;
            }
        }
        return ans.next;
    }
}

 时间复杂度O(kn)。

然后参考discuss,得到递归算法:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode mergeKLists(ListNode[] lists) {
        return partition(lists,0,lists.length-1);
    }
    private ListNode partition(ListNode[] lists,int start,int end) {
        if(start==end) {
            return lists[start];
        }
        if(start<end) {
            int mid = (start+end)/2;
            ListNode l1 = partition(lists,start,mid);
            ListNode l2 = partition(lists,mid+1,end);
            return mergeTwoLists(l1,l2);
        }
        else return null;
    }
    //This function is from Merge Two Sorted Lists.
    public static ListNode merge(ListNode l1,ListNode l2){
        if(l1==null) return l2;
        if(l2==null) return l1;
        if(l1.val<l2.val){
            l1.next=merge(l1.next,l2);
            return l1;
        }else{
            l2.next=merge(l1,l2.next);
            return l2;
        }
    }
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        if(l1==null) return l2;
        if(l2==null) return l1;
        ListNode ans,p;
        if(l1.val<=l2.val){
            ans = l1;p=ans;
            l1=l1.next;
        }
        else{
            ans = l2;p=ans;
            l2= l2.next;
        }
        while(l1!=null||l2!=null){
            if(l1==null){
                p.next=l2;
                break;
            }
            if(l2==null){
                p.next=l1;
                break;
            }
            if(l1.val<=l2.val){
                p.next = l1;
                l1 = l1.next;
                p = p.next;
            }
            else{
                p.next = l2;
                l2 = l2.next;
                p = p.next;
            }
        }
        return ans;
    }
}

用递归的2sortedlists算法,一次6ms,两次11ms;用非递归的,一次7ms,一次8ms,一次11ms。都基本在90%,可以了。

不过还有一种小根堆的做法,有空可以学习学习。

posted @ 2019-03-21 20:03  大胖子球花  阅读(100)  评论(0)    收藏  举报