问题描述
Sort a linked list in O(n log n) time using constant space complexity.
对链表进行排序,要求时间复杂度为O(nlog(n))
,空间复杂度为O(1)
举个例子:
Input: 4->2->1->3
Output: 1->2->3->4
解法1
Thanks 花花酱 LeetCode 148. Sort List - 刷题找工作 EP211{:target=”_blank”}
先提供一个时间复杂度为O(nlog(n))
、空间复杂度为O(log(n))
的版本:
主要是利用归并
思想:
来看下实现:
class Solution {
public ListNode sortList(ListNode head) {
if (head == null || head.next == null){
return head;
}
ListNode fast = head;
ListNode slow = head;
ListNode pre = head;
while (fast != null && fast.next != null){
pre = slow;
fast = fast.next.next;
slow = slow.next;
}
pre.next = null;
fast = head;
ListNode l1 = sortList(fast);
ListNode l2 = sortList(slow);
return merge(l1, l2);
}
private ListNode merge(ListNode l1, ListNode l2){
ListNode dummy = new ListNode(-1);
ListNode cur = dummy;
while (l1 != null && l2 != null){
if (l1.val <= l2.val){
cur.next = l1;
cur = l1;
l1 = l1.next;
} else {
cur.next = l2;
cur = l2;
l2 = l2.next;
}
}
if (l1 != null) cur.next = l1;
if (l2 != null) cur.next = l2;
return dummy.next;
}
}
Enjoy it !