148. Sort List

Posted panini

tags:

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

题目:

Sort a linked list in O(n log n) time using constant space complexity.

链接: http://leetcode.com/problems/sort-list/

6/12/2017

10ms, 24%,merge sort, 并不满足constant space complexity的要求

需要重写constant space的

 1 public class Solution {
 2     public ListNode sortList(ListNode head) {
 3         if (head == null || head.next == null) {
 4             return head;
 5         }
 6         ListNode mid = findMid(head);
 7         ListNode second = sortList(mid.next);
 8         mid.next = null;
 9         ListNode first = sortList(head);
10         return merge(first, second); 
11     }
12     private ListNode findMid(ListNode head) {
13         if (head == null || head.next == null) {
14             return head;
15         }
16         ListNode slow = head, fast = head;
17 
18         while (fast.next != null && fast.next.next != null) {
19             slow = slow.next;
20             fast = fast.next.next;
21         }
22         return slow;
23     }
24     private ListNode merge(ListNode first, ListNode second) {
25         ListNode dummy = new ListNode(-1);
26         ListNode cur = dummy;
27         while (first != null || second != null) {
28             if (first == null) {
29                 cur.next = second;
30                 break;
31             } else if (second == null) {
32                 cur.next = first;
33                 break;
34             } else {
35                 if (first.val < second.val) {
36                     cur.next = first;
37                     first = first.next;
38                 } else {
39                     cur.next = second;
40                     second = second.next;
41                 }
42             }
43             cur = cur.next;
44         }
45         return dummy.next;
46     }
47 }

用bottom-up的方法可以避免O(logn)的空间复杂度。直接从最低层2个元素开始,然后4个元素,直到合并整个链表

有解释的代码

https://discuss.leetcode.com/topic/10382/bottom-to-up-not-recurring-with-o-1-space-complextity-and-o-nlgn-time-complextity

解释

https://discuss.leetcode.com/topic/4860/java-solution-with-strict-o-1-auxiliary-space-complexity

更多讨论

https://discuss.leetcode.com/category/156/sort-list

 

以上是关于148. Sort List的主要内容,如果未能解决你的问题,请参考以下文章

148. Sort List

[LeetCode] 148. Sort List

148. Sort List

[Lintcode]98. Sort List/[Leetcode]148. Sort List

148. Sort List

148. Sort List