Given the head
of a linked list, return the list after sorting it in ascending order.
Follow up: Can you sort the linked list in O(n logn)
time and O(1)
memory (i.e. constant space)?
Example 1:
Input: head = [4,2,1,3] Output: [1,2,3,4]
Example 2:
Input: head = [-1,5,3,4,0] Output: [-1,0,3,4,5]
Example 3:
Input: head = [] Output: []
Constraints:
- The number of nodes in the list is in the range
[0, 5 * 104]
. -105 <= Node.val <= 105
排序链表。
题意是给你链表的头结点 head
,请将其按升序排列并返回排序后的链表,并满足时间O(nlogn),空间O(1)的要求。
按照题目要求,因为时间是nlogn,所以思路只能是merge sort。思路是找到链表的中点,然后用merge sort的思路递归再把链表一点点拼凑回去。
时间O(nlogn)
空间O(n)
JavaScript实现
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 };
Java实现
1 class Solution { 2 public ListNode sortList(ListNode head) { 3 // corner case 4 if (head == null || head.next == null) { 5 return head; 6 } 7 8 // normal case 9 ListNode middle = getMiddle(head); 10 ListNode next = middle.next; 11 middle.next = null; 12 return merge(sortList(head), sortList(next)); 13 } 14 15 private ListNode getMiddle(ListNode head) { 16 ListNode slow = head; 17 ListNode fast = head; 18 while (fast.next != null && fast.next.next != null) { 19 slow = slow.next; 20 fast = fast.next.next; 21 } 22 return slow; 23 } 24 25 private ListNode merge(ListNode a, ListNode b) { 26 ListNode dummy = new ListNode(0); 27 ListNode cur = dummy; 28 while (a != null && b != null) { 29 if (a.val < b.val) { 30 cur.next = a; 31 a = a.next; 32 } else { 33 cur.next = b; 34 b = b.next; 35 } 36 cur = cur.next; 37 } 38 if (a == null) { 39 cur.next = b; 40 } 41 if (b == null) { 42 cur.next = a; 43 } 44 return dummy.next; 45 } 46 }
相关题目