Merge k Sorted Lists

Posted YuriFLAG

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Merge k Sorted Lists相关的知识,希望对你有一定的参考价值。

思路: 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的主要内容,如果未能解决你的问题,请参考以下文章

leetcode-Merge k Sorted Lists

LeetCode 23 Merge k Sorted Lists

23. Merge k Sorted Lists

LeetCode-------merge-k-sorted-lists

leetcode23. Merge k Sorted Lists

Leetcode 23.Merge Two Sorted Lists Merge K Sorted Lists