[LeetCode] 148. Sort List

时间:2019-11-10 10:22:46   收藏:0   阅读:100

给链表排序。题意是给一个链表,请对其排序,并满足时间O(nlogn),空间O(1)的要求。

按照题目要求,因为时间是nlogn,所以自然而然想到偏向二分的做法,但是我是真做不到空间O(1),我只会用递归的方法,空间是O(n)。思路是找到链表的中点,然后用merge sort的思路递归再把链表一点点拼凑回去。

时间O(nlogn)

空间O(n)

 1 /**
 2  * @param {ListNode} head
 3  * @return {ListNode}
 4  */
 5 var sortList = function(head) {
 6     // corner case
 7     if (head === null || head.next === null) {
 8         return head;
 9     }
10     let middle = findMiddle(head);
11     let next = middle.next;
12     middle.next = null;
13     return merge(sortList(head), sortList(next));
14 };
15 
16 var findMiddle = function(head) {
17     let slow = head;
18     let fast = head;
19     while (fast.next !== null && fast.next.next !== null) {
20         slow = slow.next;
21         fast = fast.next.next;
22     }
23     return slow;
24 };
25 
26 var merge = function(a, b) {
27     let dummy = new ListNode(0);
28     let cur = dummy;
29     while (a !== null && b !== null) {
30         if (a.val < b.val) {
31             cur.next = a;
32             a = a.next;
33         } else {
34             cur.next = b;
35             b = b.next;
36         }
37         cur = cur.next;
38     }
39     if (a === null) cur.next = b;
40     else cur.next = a;
41     return dummy.next;
42 };

 

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!