[LeetCode]148. Sort List鏈表歸併排序

要求時間複雜度O(nlogn),空間複雜度O(1),採用歸併排序html

傳統的歸併排序空間複雜度是O(n),緣由是要用一個數組表示合併後的數組,可是這裏用鏈表表示有序鏈表合併後的鏈表,因爲鏈表空間複雜度是O(1),因此能夠。數組

鏈表問題常常出現TLE問題或者MLE問題,這時候要檢查鏈表拼接過程或者循環過程,看有沒有死循環spa

public ListNode sortList(ListNode head) {
        if (head==null||head.next==null) return head;
        //利用快慢指針找到鏈表中點,並分紅兩部分遞歸
        //要設置一個超前節點記錄慢指針前一個節點做爲前部分末尾
        ListNode slow = head,fast = head,pre = null;
        while (fast!=null&&fast.next!=null)
        {
            pre = slow;
            slow = slow.next;
            fast = fast.next.next;
        }
        //前半部分
        pre.next = null;
        ListNode l1 = sortList(head);
        ListNode l2 = sortList(slow);
        return merge(l1,l2);
    }
    public ListNode merge(ListNode l1,ListNode l2)
    {
        //設置超前節點
        ListNode pre = new ListNode(0),temp = pre;
        while (l1!=null&&l2!=null)
        {
            if (l1.val<l2.val)
            {
                temp.next = l1;
                l1 = l1.next;
            }
            else {
                temp.next = l2;
                l2 = l2.next;
            }
            temp = temp.next;
        }
        if (l1!=null) temp.next = l1;
        if (l2!=null) temp.next = l2;
        return pre.next;
    }

歸併排序請看:http://www.cnblogs.com/stAr-1/p/8445377.html指針

相關文章
相關標籤/搜索