Middle-题目97:148. Sort List

本文介绍了一种使用快速排序算法对单链表进行排序的方法,该方法的时间复杂度为O(nlogn),空间复杂度为O(1)。通过将链表分为小于、等于和大于基准值三个子链表,递归地进行排序并合并。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目原文:
Sort a linked list in O(n log n) time using constant space complexity.
题目大意:
对一个单链表排序,要求时间复杂度O(nlogn),空间复杂度O(1)
题目分析:
参考discuss中的算法,使用快排,取pivot为第一个节点值。
源码:(language:java)

public class Solution {
    public ListNode sortList(ListNode h){
        if(h == null || h.next == null)
            return h;

        /*split into three list*/
        ListNode fakesmall = new ListNode(0), small = fakesmall;
        ListNode fakelarge = new ListNode(0), large = fakelarge;
        ListNode fakeequal = new ListNode(0), equal = fakeequal;

        ListNode cur = h; // pivot is h.
        while(cur != null){
            if(cur.val < h.val){
                small.next = cur;
                small = small.next;
            }
            else if(cur.val == h.val){
                equal.next = cur;
                equal = equal.next;
            }
            else{
                large.next = cur;
                large = large.next;
            }

            cur = cur.next;
        }

        // put an end.
        small.next = equal.next = large.next = null;
        // merge them and return . merge reusing below one. merge for quicksort should be simplified. 
        return merge(merge(sortList(fakesmall.next), sortList(fakelarge.next)),fakeequal.next) ;
    }
    private ListNode merge(ListNode h, ListNode m){
        ListNode fake = new ListNode(0), cur = fake;

        while(h != null && m != null){

            if(h.val < m.val){
                cur.next = h;
                h = h.next;
            }
            else{
                cur.next = m;
                m = m.next;
            }
            cur = cur.next;
        }

        cur.next = (h == null ? m : h);

        return fake.next;
    }
}

成绩:
8ms,beats 42.09%,众数8ms,31.36%
cmershen的碎碎念:
数组的快排中pivot是使用三者取中法,而链表不是随机存取的,使用三者取中法要遍历一次链表,反而不能加速。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值