148. Sort List

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

Solution:Merge归并排序 分治思想

思路:
pre-order部分:将list分为左右两部分(中间处断开以便处理)
Divide: 将分开的两部分 递归去处理
Conquer: 将递归得到的分别排好序的左右结果 进行 merge排序:直接使用21题mergeTwoLists方法:http://www.jianshu.com/p/ddad4576e950
注意递归终止条件,以及传递关系(input:两个断开的序列,return:排好序的头节点)
Time Complexity: T(N) = 2T(N / 2) + O(N) => O(NlogN)
Space Complexity: O(logN) 递归缓存logN层

Solution Code:

class Solution {
  
    public ListNode sortList(ListNode head) {
        if (head == null || head.next == null)
        return head;
        
        // step 1. cut the list to two halves
        ListNode slow = head;
        ListNode fast = head;
        while(fast.next != null && fast.next.next != null){ 
            slow = slow.next;
            fast = fast.next.next;
        }

        //  1     ->    2    ->    3    ->    4    ->  null
        //             slow   right_start    fast

        ListNode right_start = slow.next;
        slow.next = null; // cut off from middle


        // step 2. sort each half
        ListNode l1 = sortList(head);
        ListNode l2 = sortList(right_start);

        // step 3. merge l1 and l2
        return mergeTwoLists(l1, l2);
    }
    
  
    private ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        ListNode cur1 = l1;
        ListNode cur2 = l2;
        
        ListNode dummy = new ListNode(0);
        ListNode cur = dummy;
        while(cur1 != null && cur2 != null) {
            if(cur1.val < cur2.val) {
                cur.next = cur1;
                cur1 = cur1.next;
            }
            else {
                cur.next = cur2;
                cur2 = cur2.next;
            }
            cur = cur.next;
        }        
        // the rest
        cur.next = cur1 == null ? cur2 : cur1;
        return dummy.next;
    }
}

你可能感兴趣的:(148. Sort List)