zoukankan      html  css  js  c++  java
  • 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 };
  • 相关阅读:
    spring整合Quartz
    Quartz基本使用
    hibernate框架基础描述
    POI技术实现对excel的导出
    CG-CTF CRYPTO部分wp
    CG-CTF web部分wp
    快速排序算法的c++实现
    tornado当用户输入的URL无效时转入设定的页面
    sicily 4699. 简单哈希
    unbutu下Io language的解释器安装
  • 原文地址:https://www.cnblogs.com/amazingzoe/p/4669609.html
Copyright © 2011-2022 走看看