Leetcode 23: Merge k Sorted Lists

Posted Keep walking

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.

 

 1 /**
 2  * Definition for singly-linked list.
 3  * public class ListNode {
 4  *     public int val;
 5  *     public ListNode next;
 6  *     public ListNode(int x) { val = x; }
 7  * }
 8  */
 9 public class Solution {
10     public ListNode MergeKLists(ListNode[] lists) {
11         if (lists == null || lists.Length == 0) return null;
12         
13         return Sort(lists, 0, lists.Length - 1);
14     }
15     
16     private ListNode Sort(ListNode[] lists, int start, int end)
17     {
18         if (start > end) 
19         {
20             return null;
21         }
22         
23         if (start == end) 
24         {
25             return lists[start];
26         }
27         
28         int mid = start + (end - start) / 2;
29         var l1 = Sort(lists, start, mid);
30         var l2 = Sort(lists, mid + 1, end);
31         
32         return Merge(l1, l2);
33     }
34     
35     private ListNode Merge(ListNode l1, ListNode l2)
36     {
37         ListNode head = new ListNode(1), cur = head;
38         
39         while (l1 != null || l2 != null)
40         {
41             if (l1 != null && l2 != null)
42             {
43                 if (l1.val <= l2.val)
44                 {
45                     cur.next = l1;
46                     l1 = l1.next;
47                 }
48                 else
49                 {
50                     cur.next = l2;
51                     l2 = l2.next;
52                 }
53             }
54             else if (l1 != null)
55             {
56                 cur.next = l1;
57                 l1 = l1.next;
58             }
59             else
60             {
61                 cur.next = l2;
62                 l2 = l2.next;
63             }
64              
65             cur = cur.next;
66         }
67         
68         return head.next;
69     }
70 }

 

以上是关于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