码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode-148-Sort List

时间:2019-02-06 22:41:27      阅读:221      评论:0      收藏:0      [点我收藏+]

标签:dup   代码   ret   tput   span   time   lex   slow   思路   

算法描述:

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

解题思路:时间复杂度O(nlogn)。写了快排感觉很奇怪,看了其他人答案,发现都是归并排序。

快排代码很乱,如下。

    ListNode* sortList(ListNode* head) {
        if(head==nullptr || head->next==nullptr) return head;
        ListNode* leftHead = new ListNode(INT_MIN);
        ListNode* rightHead = new ListNode(INT_MIN);
        ListNode* lc = leftHead;
        ListNode* rc = rightHead;
        
        ListNode* pivot = head;
        ListNode* cur = head->next;
        while(cur!=nullptr){
            if(cur->val < pivot->val){
                lc->next = cur;
                lc = lc->next;
            }else {
                rc->next = cur;
                rc = rc->next;
            }
            cur=cur->next;
        }
        lc->next = nullptr;
        rc->next = nullptr;
        
        leftHead->next = sortList(leftHead->next);
        rightHead->next = sortList(rightHead->next);
        cur = leftHead;
        while(cur->next!=nullptr) cur=cur->next;
        cur->next=pivot;
        cur->next->next = rightHead->next;
        return leftHead->next;
    }

归并排序代码:

 ListNode* sortList(ListNode* head) {
        if(head==nullptr || head->next==nullptr) return head;
        ListNode* fast = head->next;
        ListNode* slow = head;
        while(fast!=nullptr && fast->next!=nullptr){
            fast=fast->next->next;
            slow=slow->next;
        }
        
        fast = slow->next;
        slow->next = nullptr;
     
        return merge(sortList(fast), sortList(head));
    }
    ListNode* merge(ListNode* l1, ListNode* l2){
        
        ListNode* dup = new ListNode(-1);
        ListNode* cur = dup;
        while(l1!=nullptr && l2!=nullptr){
            if(l1->val < l2->val){
                cur->next=l1;
                l1=l1->next;
            }else{
                cur->next=l2;
                l2=l2->next;
            }
            cur=cur->next;
        }
        
        if(l1!=nullptr) cur->next = l1;
        else cur->next = l2;
        return dup->next;
    }

 

LeetCode-148-Sort List

标签:dup   代码   ret   tput   span   time   lex   slow   思路   

原文地址:https://www.cnblogs.com/nobodywang/p/10354102.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!