zoukankan      html  css  js  c++  java
  • 【leetcode】148. Sort List

    题目说明

    https://leetcode-cn.com/problems/sort-list/description/
    在 O(n log n) 时间复杂度和常数级空间复杂度下,对链表进行排序。

    解法1

    使用归并排序对链表进行排序

    /*
     * 时间复杂度:O(nlogn)
     * 归并排序的递归实现
     */
    ListNode* sortList(ListNode* head) {
        if (head == NULL || head->next == NULL)
            return head;
        ListNode *slow = head;
        ListNode *fast = head->next;
    
        while(fast && fast->next){
            fast = fast->next->next;
            slow = slow->next;
        }
    
        ListNode *half = slow->next;
        slow->next = NULL;
    
        return merge(sortList(head),sortList(half));
    }
    
    ListNode *merge(ListNode* head1,ListNode* head2)
    {
        ListNode *dummy = new ListNode(0);
        ListNode *l3 = dummy;
    
        ListNode *l1 = head1;
        ListNode *l2 = head2;
    
        while(l1 && l2 ){
            if (l1->val < l2->val){
                l3->next = l1;
                l1 = l1->next;
            } else if (l1->val >= l2->val){
                l3->next = l2;
                l2 = l2->next;
            }
            l3 = l3->next;
        }
        ListNode *last = (l1 == NULL)?l2:l1;
        l3->next = last;
    
        ListNode *ret = dummy->next;
        delete dummy;
        return ret;
    }
  • 相关阅读:
    ElasticSearch-生命周期管理
    Alpha 冲刺五
    Alpha 冲刺四
    Alpha 冲刺三
    Alpha 冲刺二
    Alpha 冲刺一
    测试随笔
    校友录
    项目需求分析(淘校)
    团队选题报告(淘校)
  • 原文地址:https://www.cnblogs.com/JesseTsou/p/9589408.html
Copyright © 2011-2022 走看看