首页 > 其他 > 详细

[LintCode] Merge k Sorted Lists

时间:2015-11-17 12:59:44      阅读:257      评论:0      收藏:0      [点我收藏+]

Merge k Sorted Lists

Merge k sorted linked lists and return it as one sorted list.

Analyze and describe its complexity.

Example

Given lists:

[
  2->4->null,
  null,
  -1->null
],

return -1->2->4->null.

 

SOLUTION:

几个list一起merge的话,应该能算是,merge 2 sorted list -->follow up-->merge 2 unsorted list -->follow up--> merge k sorted list,一个follow up的过程。这个一样用递归去做,简单明了。做一个递归函数helper();这是因为传入参数跟原来的不一样,不然是可以直接递归的。然后list当然也要二分一下,然后需要用的就是list的size,然后,left = helper(lists, start, mid); right = helper(lists, mid + 1, end); 最后merge(left, right)就OK了。

技术分享
/**
 * Definition for ListNode.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int val) {
 *         this.val = val;
 *         this.next = null;
 *     }
 * }
 */ 
public class Solution {
    /**
     * @param lists: a list of ListNode
     * @return: The head of one sorted list.
     */
    public ListNode mergeKLists(List<ListNode> lists) {  
        if (lists == null || lists.size() == 0){
            return null;
        }
        int size = lists.size();
        return helper(lists, 0, size - 1);
    }
    private ListNode helper(List<ListNode> lists, int start, int end){
        if (start < end){
            int mid = start + (end - start) / 2;
            return merge(helper(lists, start, mid), helper(lists, mid + 1, end));
        }
        return lists.get(start);
    }
    private ListNode merge(ListNode l1, ListNode l2){
        if (l1 == null){
            return l2;
        }
        if (l2 == null){
            return l1;
        }
        ListNode dummy = new ListNode(0);
        ListNode head = dummy;
        while (l1 != null && l2 != null){
            if (l1.val < l2.val){
                head.next = l1;
                l1 = l1.next;
                head = head.next;
            } else {
                head.next = l2;
                l2 = l2.next;
                head = head.next;
            }
        }
        if (l1 != null){
            head.next = l1;
        }
        if (l2 != null){
            head.next = l2;
        }
        return dummy.next;
    }
}
View Code

 

[LintCode] Merge k Sorted Lists

原文:http://www.cnblogs.com/tritritri/p/4971163.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!