美文网首页
148 Sort List

148 Sort List

作者: 烟雨醉尘缘 | 来源:发表于2019-07-21 15:56 被阅读0次

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

    Example:

    Input: 4->2->1->3
    Output: 1->2->3->4

    Input: -1->5->3->4->0
    Output: -1->0->3->4->5

    解释下题目:

    链表排序,时间复杂度要求nlogn,且空间复杂度是常量

    1. 方法1

    实际耗时:xxms

    public ListNode sortList(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }
        ListNode fast = head;
        ListNode slow = head;
        ListNode pre = slow;
        while (fast != null && fast.next != null) {
            fast = fast.next.next;
            pre = slow;
            slow = slow.next;
        }
        // now slow is in the middle
        // !!! don't forget to cut this list
        pre.next = null;
        return mergeList(sortList(head), sortList(slow));
    }
    
    private ListNode mergeList(ListNode l1, ListNode l2) {
        ListNode res = new ListNode(0);
        ListNode cur = res;
        while (l1 != null && l2 != null) {
            if (l1.val < l2.val) {
                cur.next = l1;
                l1 = l1.next;
                cur = cur.next;
            } else {
                cur.next = l2;
                l2 = l2.next;
                cur = cur.next;
            }
        }
        if (l1 != null) {
            cur.next = l1;
        }
        if (l2 != null) {
            cur.next = l2;
        }
        return res.next;
    }
    

      思路跟数组的排序也是一样的,找到中间,切断,然后一分为二继续,而且我感觉merge甚至比数组还简单。唯一需要注意的就是记得切断
      而且题目说的是常量空间,其实递归的话应该就不算了,但是如果要nlogn确实也只有快排了。

    时间复杂度O(nlogn)
    空间复杂度O(1)

    相关文章

      网友评论

          本文标题:148 Sort List

          本文链接:https://www.haomeiwen.com/subject/sftvlctx.html