LeetCode 148. Sort List

本文介绍了一种使用常数空间复杂度在O(nlogn)时间内对链表进行排序的方法。文章详细讨论了使用mergesort算法的尝试及其挑战,并提供了具体的代码实现。

description:
Sort a linked list in O(n log n) time using constant space complexity.
题目要求使用O(nlogn)的时间复杂度和确定的控件复杂度,但是一开始的时候没有注意到确定的个空间复杂度这一个词,结果使用了merge sort的排序方式。
没有通过测试,但是也可以拿出来写一写,其中的有些内容还是非常有意思的。

merge sort是一种稳定排序,使用分值的方式进行实现。
开始的时候,要有首先计算ListNode right,然后让middle.next = null,此处是为了让left的内容随着right变化,否则就可能出现内存溢出的情况。

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ListNode sortList(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }
        ListNode middle = findMiddle(head);
        ListNode right = sortList(middle.next);
        middle.next = null;
        ListNode left = sortList(head);
        ListNode value = mergeListNode(left, right);
        return value;
    }
    private ListNode findMiddle(ListNode node) {
        ListNode slow = node;
        ListNode fast = node.next;
        while (fast.next != null && fast.next.next != null) {
            slow = slow.next;
            fast = fast.next.next;
        }
        return slow;
    }
    private ListNode mergeListNode(ListNode left, ListNode right) {
        ListNode dummy = new ListNode(0);
        ListNode head = dummy;
        while (left != null && right != null) {
            if (left.val > right.val) {
                head.next = right;
                right = right.next;
            } else {
                head.next = left;
                left.next = left.next;
            }
            head = head.next;
        }
        if (left != null) {
            head.next = left;
        } else {
            head.next = right;
        }
        return dummy.next;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ncst

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值