• Sort List


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

    Analyse: When it comes to O(nlogn), we need to think of sort algorithms like merge sort, quick sort, and heap sort. Choosing merge sort, we can reuse the code from merge two sorted lists. 

    Runtime: 60ms.

     1 /**
     2  * Definition for singly-linked list.
     3  * struct ListNode {
     4  *     int val;
     5  *     ListNode *next;
     6  *     ListNode(int x) : val(x), next(NULL) {}
     7  * };
     8  */
     9 class Solution {
    10 public:
    11     ListNode* sortList(ListNode* head) {
    12         if(!head || !head->next) return head;
    13         
    14         ListNode* slow = head;
    15         ListNode* fast = head;
    16         while(fast->next && fast->next->next){
    17             fast = fast->next->next;
    18             slow = slow->next;
    19         }
    20         fast = slow->next;
    21         slow->next = nullptr; //break the list into two parts
    22         
    23         return merge2lists(sortList(head), sortList(fast));
    24     }
    25     ListNode* merge2lists(ListNode *l1, ListNode *l2) {
    26         ListNode pre(-1);
    27         
    28         for(ListNode* p = ⪯ l1 || l2; p = p->next){
    29             int val1 = l1 == nullptr ? INT_MAX : l1->val;
    30             int val2 = l2 == nullptr ? INT_MAX : l2->val;
    31             
    32             if(val1 > val2){
    33                 p->next = l2;
    34                 l2 = l2->next;
    35             }
    36             else{
    37                 p->next = l1;
    38                 l1 = l1->next;
    39             }
    40         }
    41         return pre.next;
    42     }
    43 };
  • 相关阅读:
    张量自动求导和计算图
    34 深入浅出 x86 中断机制(下)
    33 深入浅出 x86 中断机制(上)
    使用STM32 PWM控制LCD背光
    32 获取物理内存容量 下
    ucGUI内存管理相关
    STM32 SPI双机通信参考
    IAR_UCOSII_UCOSIII
    每日总结
    每日总结
  • 原文地址:https://www.cnblogs.com/amazingzoe/p/4669609.html
Copyright © 2020-2023  润新知