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 };
  • 相关阅读:
    SpringBook+Lombok 使用教程
    SpringBoot + Swagger Demo
    SpringBoot+Mybatis_Plus Generator
    Ubuntu下创建apt源
    Mysql优化建议
    Zabbix批量添加Hosts
    批量安装Zabbix_Agent
    CentOS7安装Zabbix
    安卓开发中的各种进度条样式
    多点触控之MotionEvent.ACTION_MASK作用
  • 原文地址:https://www.cnblogs.com/amazingzoe/p/4669609.html
Copyright © 2011-2022 走看看