首页 > 其他 > 详细

Merge k Sorted Lists

时间:2016-03-31 12:26:27      阅读:219      评论:0      收藏:0      [点我收藏+]

思路: 1.Divide & Conquer 2.Merge sorted list.

 1 /**
 2  * Definition for singly-linked list.
 3  * public class ListNode {
 4  *     int val;
 5  *     ListNode next;
 6  *     ListNode(int x) { val = x; }
 7  * }
 8  */
 9 public class Solution {
10     public ListNode mergeKLists(ListNode[] lists) {
11          if (lists == null || lists.length == 0) {
12             return null;
13         }
14         return mergeHelper(lists, 0, lists.length - 1);
15     }
16     
17     private ListNode mergeHelper(ListNode[]  lists, int start, int end) {
18         if (start >= end) {
19             return lists[start];
20         }
21         int mid = start + (end - start) / 2;
22         ListNode left = mergeHelper(lists, start, mid);
23         ListNode right = mergeHelper(lists, mid + 1, end);
24         return merge(left, right);
25     }
26     
27     private ListNode merge(ListNode list1, ListNode list2) {
28         ListNode dummy = new ListNode(0);
29         ListNode tail = dummy;
30         while (list1 != null && list2 != null) {
31             if (list1.val < list2.val) {
32                 tail.next = list1;
33                 list1 = list1.next;
34                 tail = tail.next;
35             } else {
36                 tail.next = list2;
37                 list2 = list2.next;
38                 tail = tail.next;
39             }
40         }
41         if (list1 != null) {
42             tail.next = list1;
43         } else {
44             tail.next = list2;
45         }
46         return dummy.next;
47     }
48 }

 

Merge k Sorted Lists

原文:http://www.cnblogs.com/FLAGyuri/p/5340343.html

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