码迷,mamicode.com
首页 > 其他好文 > 详细

23. Merge k Sorted Lists

时间:2016-04-17 06:41:51      阅读:160      评论:0      收藏:0      [点我收藏+]

标签:

    /*
     * 23. Merge k Sorted Lists 
     * 2016-4-16 By Mingyang
     * 正如merge 2 list里面说的,可以利用那个来进行简化
     */
    public ListNode mergeKLists(ListNode[] lists) {
        if (lists.length == 0) {
            return null;
        }
        return mergeHelper(lists, 0, lists.length - 1);
    }

    private ListNode mergeHelper(ListNode[] lists, int start, int end) {
        if (start == end) {
            return lists[start];
        }
        int mid = start + (end - start) / 2;
        ListNode left = mergeHelper(lists, start, mid);
        ListNode right = mergeHelper(lists, mid + 1, end);
        return mergeTwoLists(left, right);
        // 运用到我们前面所说的merge two lists的方法
    }
     public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
            if(l1==null) return l2;
            if(l2==null) return l1;
            if(l1.val<l2.val){
                l1.next=mergeTwoLists(l1.next,l2);
                return l1;
            }else{
                l2.next=mergeTwoLists(l1,l2.next);
                return l2;
            }
       }

 

23. Merge k Sorted Lists

标签:

原文地址:http://www.cnblogs.com/zmyvszk/p/5400161.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!