[LeetCode] 148. Sort List

linspiration發表於2019-01-19

Problem

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

Example 1:

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

Example 2:

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

Solution

Merge Sort

Space: O(logN)

Time: O(NlogN)

class Solution {
    public ListNode sortList(ListNode head) {
        if (head == null || head.next == null) return head;
        ListNode slow = head, fast = head, split = head;
        while (fast != null && fast.next != null) {
            split = slow;
            fast = fast.next.next;
            slow = slow.next;
        }
        split.next = null;
        ListNode l1 = sortList(slow);
        ListNode l2 = sortList(head);
        head = merge(l1, l2);
        return head;
    }
    private ListNode merge(ListNode l1, ListNode l2) {
        ListNode dummy = new ListNode(0), head = dummy;
        while (l1 != null && l2 != null) {
            if (l1.val <= l2.val) {
                head.next = l1;
                l1 = l1.next;
            } else {
                head.next = l2;
                l2 = l2.next;
            }
            head = head.next;
        }
        if (l1 != null) head.next = l1;
        if (l2 != null) head.next = l2;
        return dummy.next;
    }
}

相關文章