leetCode 23. Merge k Sorted Lists

Posted yfs123456

tags:

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

 

Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.

Example:

Input:
[
  1->4->5,
  1->3->4,
  2->6
]
Output: 1->1->2->3->4->4->5->6

采用分治算法,时间复杂度为nlog(n),同分治排序。

 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 class Solution 
10     //返回lists数组第low至high位置(不包括high位置)的链表merge后的链表
11     public ListNode result(ListNode[] lists,int low,int high)
12         if (low+1==high) return lists[low];
13         int mid=(low+high)/2;
14         ListNode left = result(lists,low,mid);
15         ListNode right = result(lists,mid,high);
16 
17         //merge left链表和right链表
18         ListNode head = new ListNode(-65535);
19         ListNode p = head;//指向head最后一个节点
20         while (left!=null && right!=null)
21             if (left.val < right.val)
22                 p.next=left;
23                 left=left.next;
24             else 
25                 p.next=right;
26                 right=right.next;
27             
28             p=p.next;
29         
30         if (left!=null)
31             p.next=left;
32         
33         if (right!=null)
34             p.next=right;
35         
36         return head.next;
37     
38 
39     public ListNode mergeKLists(ListNode[] lists) 
40         if (lists.length==0) return null;
41         if (lists.length==1) return lists[0];
42         ListNode result = result(lists, 0, lists.length);
43         return result;
44     
45 

 

以上是关于leetCode 23. Merge k Sorted Lists的主要内容,如果未能解决你的问题,请参考以下文章

[LeetCode] 23. Merge k Sorted Lists

[LeetCode] 23. Merge k Sorted Lists 合并k个有序链表

[LeetCode]23. Merge k Sorted Lists

leetcode23. Merge k Sorted Lists

leetCode 23. Merge k Sorted Lists

leetcode 23. Merge k Sorted Lists