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 };
  • 相关阅读:
    Centos下安装Spark
    Centos下安装Scala(2)
    Spark寒假实验1
    Mybatis 学习记录 续
    Centos下安装Scala(1)
    putty【cmd命令】
    cmd查看命令所在【全路径】
    linux开关机相关
    Xml WebService完全实例解析(一)
    Xml WebService完全实例解析(二)
  • 原文地址:https://www.cnblogs.com/amazingzoe/p/4669609.html
Copyright © 2011-2022 走看看