[LeetCode]Sort List

本文介绍了一种在O(nlogn)时间内使用常数空间复杂度对链表进行排序的方法,采用归并排序策略实现。文章详细解释了如何找到中间节点、切断链表并递归排序两部分链表,最后通过合并两个已排序链表完成整个排序过程。

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


本题难度Medium。

归并

【复杂度】
时间 O(Nlog(N)) 空间 O(1)

【思路】
题目要求时间复杂度O(Nlog(N)) 常数空间。对于单向链表适合用归并排序,双向链表适合用快速排序。

【注意】

  1. 第4行的检测是不可或缺的,否则会造成快慢法以及第12行出现”NullPoint”错误:
if(head==null||head.next==null)return head;
  1. 第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;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值