Question
Sort a linked list in O(n log n) time using constant space complexity.
本题难度Medium。
归并
【复杂度】
时间 O(Nlog(N)) 空间 O(1)
【思路】
题目要求时间复杂度O(Nlog(N)) 常数空间。对于单向链表适合用归并排序,双向链表适合用快速排序。
【注意】
- 第4行的检测是不可或缺的,否则会造成快慢法以及第12行出现”NullPoint”错误:
if(head==null||head.next==null)return head;
- 第12行对链表的剪断也是必须的,否则子链表的排序将会越界。
//cut off the 2 lists
fast=slow;slow=slow.next;fast.next=null;
【代码】
public class Solution {
public ListNode sortList(ListNode head) {
//require
if(head==null||head.next==null)return head;
//find the middle node
ListNode fast=head,slow=head;
while(fast.next!=null&&fast.next.next!=null){
fast=fast.next.next;
slow=slow.next;
}
//cut off the 2 lists
fast=slow;slow=slow.next;fast.next=null;
//invariant
ListNode l1=sortList(head),l2=sortList(slow);
return mergeList(l1,l2);
}
private ListNode mergeList(ListNode l1,ListNode l2){
//require
ListNode fake=new ListNode(0),cur=fake;
//invariant
while(l1!=null&&l2!=null){
if(l1.val<l2.val){
cur.next=l1;
l1=l1.next;
}else{
cur.next=l2;
l2=l2.next;
}
cur=cur.next;
}
if(l1==null)cur.next=l2;
else cur.next=l1;
//ensure
return fake.next;
}
}