[LeetCode] 148. Sort List

linspiration

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;
    }
}
阅读 666

Road to Glory
對酒當歌,人生幾何?譬如朝露,去日苦多。
161 声望
31 粉丝
0 条评论
你知道吗?

161 声望
31 粉丝
宣传栏