Quick Sort 4 ms beats 96.51%


  • 2
    D
    public ListNode sortList(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }
        
        ListNode dummy1 = new ListNode(0);
        ListNode dummy2 = new ListNode(0);
        ListNode prev1 = dummy1;
        ListNode prev2 = dummy2;
        ListNode node = head.next;
        ListNode prev = head;
        while (node != null) {
            if (node.val < head.val) {
                prev1.next = node;
                prev1 = prev1.next;
            } else if (node.val > head.val) {
                prev2.next = node;
                prev2 = prev2.next;
            } else {
                prev.next = node;
                prev = prev.next;
            }
            node = node.next;
        }
        
        prev1.next = prev2.next = prev.next = null;
        dummy1.next = sortList(dummy1.next);
        dummy2.next = sortList(dummy2.next);
        prev1 = dummy1;
        while (prev1.next != null) {
            prev1 = prev1.next;
        }
        
        prev1.next = head;
        prev.next = dummy2.next;
        return dummy1.next;
    }

  • 0
    A

    3-way quicksort, very nicely done :)


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.