148. Sort List

来源:互联网 发布:质量软件 编辑:程序博客网 时间:2024/06/05 20:50

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


摘自:

https://leetcode.com/discuss/1709/have-pretty-mergesort-method-anyone-speed-reduce-memory-usage

http://blog.csdn.net/jiadebin890724/article/details/21334059

对一个链表进行排序,且时间复杂度要求为 O(n log n) ,空间复杂度为常量。一看到 O(n log n) 的排序,首先应该想到归并排序和快速排序,但是通常我们使用这两种排序方法时都是针对数组的,现在是链表了。
        归并排序法:在动手之前一直觉得空间复杂度为常量不太可能,因为原来使用归并时,都是 O(N)的,需要复制出相等的空间来进行赋值归并。对于链表,实际上是可以实现常数空间占用的。利用归并的思想,递归地将当前链表分为两段,然后merge,分两段的方法是使用 fast-slow 法,用两个指针,一个每次走两步,一个走一步,直到快指针走到了末尾,慢指针所在位置就是中间位置,这样就分成了两段。merge时,把两段头部节点值比较,用一个 p 指向较小的,且记录第一个节点,然后 两段的头一步一步向后走,p也一直向后走,总是指向较小节点,直至其中一个头为NULL,处理剩下的元素。最后返回记录的头即可。

public ListNode sortList(ListNode head) {        if (head == null || head.next == null)            return head;        ListNode f = head.next.next;        ListNode p = head;        while (f != null && f.next != null) {            p = p.next;            f =  f.next.next;        }        ListNode h2 = sortList(p.next);        p.next = null;        return merge(sortList(head), h2);    }    public ListNode merge(ListNode h1, ListNode h2) {        ListNode hn = new ListNode(Integer.MIN_VALUE);        ListNode c = hn;        while (h1 != null && h2 != null) {            if (h1.val < h2.val) {                c.next = h1;                h1 = h1.next;            }            else {                c.next = h2;                h2 = h2.next;            }            c = c.next;        }        if (h1 != null)            c.next = h1;        if (h2 != null)            c.next = h2;        return hn.next;    }


0 0