zoukankan      html  css  js  c++  java
  • LC.148.Sort List

    https://leetcode.com/problems/sort-list/description/
    Sort a linked list in O(n log n) time using constant space complexity.
    找到中点之后的处理,和 143 "Reorder List" 是一样的 : 然后把tail 传后面去
    ListNode tail = mid.next ;
    //cut it off
    mid.next = null ;

    time: o(nlogn) space: o(n): recursive with n stacks
     1 public ListNode sortList(ListNode head) {
     2         if (head == null || head.next == null) return head ;
     3         //merge sort
     4         //find the mid,
     5         ListNode mid = getMid(head) ;
     6         ListNode tail = mid.next ;
     7         //cut it off
     8         mid.next = null ;
     9         //recursive
    10         ListNode firstHead = sortList(head) ;
    11         ListNode secHead = sortList(tail) ;
    12         //merge: same logic as merge two sorted list
    13          ListNode newHead = merge(firstHead, secHead);
    14          return newHead;
    15     }
    16 
    17     private ListNode merge(ListNode firstHead, ListNode secHead) {
    18         ListNode dummy = new ListNode(0) ;
    19         ListNode curr = dummy ;
    20         while (firstHead != null && secHead != null){
    21             if (firstHead.val<secHead.val){
    22                 curr.next = firstHead ;
    23                 firstHead = firstHead.next ;
    24                 curr = curr.next ;
    25             } else{
    26                 curr.next = secHead ;
    27                 secHead = secHead.next ;
    28                 curr = curr.next ;
    29             }
    30         }
    31         //corner case: either one side left
    32         if (firstHead!=null){
    33             curr.next = firstHead ;
    34         }
    35         if (secHead != null){
    36             curr.next = secHead ;
    37         }
    38         return dummy.next ;
    39     }
    40 
    41     private ListNode getMid(ListNode head){
    42         if (head == null ) return head ;
    43         ListNode fast = head , slow = head ;
    44         while(fast != null && fast.next != null && fast.next.next != null){
    45             fast = fast.next.next ;
    46             slow = slow.next ;
    47         }
    48         return slow ;
    49     }
  • 相关阅读:
    北京初“探”,还是初“谈”
    hadoop集群安装(多机,非伪集群)
    iOS8下注冊push方式变更
    Linux文件编辑命令具体整理
    HDU 1260
    二叉树遍历(前序、中序、后序、层次、深度优先、广度优先遍历)
    关于Linux静态库和动态库的分析
    JavaScript特效之前进,后退(返回上一级)
    具体解释Hibernate中的事务
    iOS开发
  • 原文地址:https://www.cnblogs.com/davidnyc/p/8471352.html
Copyright © 2011-2022 走看看