LeetCode148. Sort List

本文介绍如何在O(nlogn)时间内对链表进行排序,并且仅使用O(1)额外空间。主要讨论了快速排序和归并排序两种方法的实现细节。

Analysis

This question requires to sort a LinkedList in O(nlogn) time and O(1) space. We know that all comparison-based sorting alrogithm have the upperbound time complexity of O(nlogn). Thus it is obvious that we are looking for some transformation of one of the following algorithms:

Implementation

Merge sort, Quick sort, Heap sort.

Considering we are dealing with a LinkedList and can only use O(1) space, we need to think of which one of the above algorithm can be applied to this situation.

Heap sort is apparently not applicable because of its space complexity.

Quick sort is applicable since, we just need to modify the corresponding partition process of quick sort.

A quick sort implmentation is showed as following.

Note that an important difference of this quick sort with a normal array quick sort is that we have to merge the resulting sub-LinkedList.

class Solution {
    public ListNode sortList(ListNode head) {
        // When the LinkedList is null or has a length of 1, no need to sort.
        if (head == null || head.next == null) {
            return head;
        }

        return quickSort(head);
    }

    private ListNode quickSort(ListNode head) {
        // Base case
        if (head == null || head.next == null) {
            return head;
        }

        ListNode fakeSmall = new ListNode(0);
        ListNode small = fakeSmall;
        ListNode fakeEqual = new ListNode(0);
        ListNode equal = fakeEqual;
        ListNode fakeLarge = new ListNode(0);
        ListNode large = fakeLarge;

        // use head as pivot
        ListNode curr = head;
        while (curr != null) {
            if (curr.val > head.val) {
                large.next = curr;
                large = large.next;
            } else if (curr.val < head.val) {
                small.next = curr;
                small = small.next;
            } else {
                equal.next = curr;
                equal = equal.next;
            }

            curr = curr.next;
        }

        small.next = null;
        large.next = null;
        equal.next = null;

        return merge(merge(quickSort(fakeLarge.next), quickSort(fakeSmall.next)), fakeEqual.next);
    }

Merge sort is also applicable, we need to change the process of finding middle point and merge. The merge is just the same as Merge 2 sorted LinkedList.

A merge sort implementation is showed as following:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode sortList(ListNode head) {
        // When the LinkedList is null or has a length of 1, no need to sort.
        if (head == null || head.next == null) {
            return head;
        }

        return mergeSort(head);
    }

    private ListNode mergeSort(ListNode head) {
        /**
         * Using merge sort to sort the 2 LinkedList recursively.
         */
        if (head.next == null) {
            return head;
        }

        // Get the middle point of the LinkedList
        ListNode middle = findMiddle(head);

        // Sort the first half
        ListNode left = mergeSort(head);

        // Sort the second half
        ListNode right = mergeSort(middle);

        return merge(left, right);
    }

    private ListNode merge(ListNode left, ListNode right) {
        // Merge 2 sorted LinkedList
        ListNode dummy = new ListNode(0);
        ListNode head = dummy;
        while (left != null && right != null) {
            if (left.val <= right.val) {
                head.next = left;
                left = left.next;
            } else {
                head.next = right;
                right = right.next;
            }
            head = head.next;
        }

        if (left != null) {
            head.next = left;
        }
        if (right != null) {
            head.next = right;
        }

        return dummy.next;
    }

    private ListNode findMiddle(ListNode head) {
        /**
         * Find the middle point of a linked list
         * And split the original LinkedList into 2 separated List by removing
         * the next pointer in the middle.
         */
        ListNode fast = head;
        ListNode slow = head;
        while (fast.next != null && fast.next.next != null) {
            slow = slow.next;
            fast = fast.next.next;
        }

        ListNode ret = slow.next;
        slow.next = null;
        return ret;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

耀凯考前突击大师

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

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

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

打赏作者

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

抵扣说明:

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

余额充值