• 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 };
  • 相关阅读:
    用Github发布静态页面
    JS实现图片放大查看
    CSS3-字体渐变色
    Eclipse切换工作空间(Workspace)
    JS打开新的窗口
    HTML中特殊符号的处理
    PHP转码函数
    SecureCRT按退格键出现^H问题解决
    商人过河问题(二)java实现
    商人过河问题(一)
  • 原文地址:https://www.cnblogs.com/amazingzoe/p/4669609.html
Copyright © 2020-2023  润新知