zoukankan      html  css  js  c++  java
  • [Leetcode] Sort List

    Sort a linked list in O(n log n) time using constant space complexity.

    Solution:

    O(nlgn)的排序算法没几个,无非就是quick sort, heap sort和merge sort. 对于链表排序来说,难点之一就是如何O(1)定位节点。如果是数组,那么可以通过下标直接找到节点,但是对于链表,很明显没有下标这个东西可以用,如果需要定位到第k个元素,只能从节点头部顺序的访问K次,但是,如果排序中每一个定位操作都要这样做的话,就太慢了。
    所以,问题其实就是,如何能够节省链表节点的定位时间。如果采用merge sort的话,就可以通过递归的特性来避免这个时间损耗。

     1 /**
     2  * Definition for singly-linked list.
     3  * class ListNode {
     4  *     int val;
     5  *     ListNode next;
     6  *     ListNode(int x) {
     7  *         val = x;
     8  *         next = null;
     9  *     }
    10  * }
    11  */
    12 public class Solution {
    13     public ListNode sortList(ListNode head) {
    14         if(head==null||head.next==null)
    15             return head;
    16         ListNode fast=head, slow=head;
    17         while(fast.next!=null&&fast.next.next!=null){
    18             fast=fast.next.next;
    19             slow=slow.next;
    20         }
    21         fast=slow.next;
    22         slow.next=null;
    23         fast=sortList(fast);
    24         slow=sortList(head);
    25         return merge(fast,slow);
    26     }
    27 
    28     private ListNode merge(ListNode fast, ListNode slow) {
    29         // TODO Auto-generated method stub
    30         ListNode result=new ListNode(-1);
    31         result.next=null;
    32         ListNode cur=result;
    33         while(fast!=null&&slow!=null){
    34             if(fast.val<slow.val){
    35                 cur.next=fast;
    36                 fast=fast.next;
    37             }else{
    38                 cur.next=slow;
    39                 slow=slow.next;
    40             }
    41             cur=cur.next;
    42         }
    43         if(fast!=null){
    44             cur.next=fast;
    45         }
    46         if(slow!=null){
    47             cur.next=slow;
    48         }    
    49         return result.next;
    50     }
    51 }
  • 相关阅读:
    nginx下pagespeed使用详解
    letsencrypt证书-使用certbot申请wildcard证书
    letsencrypt证书-管理工具certbot
    tcpdump使用
    elasticsearch增删改查操作
    elasticsearch安装中文分词器
    dragstart drag dragend dragenter dragover dragleave drop
    js如何准确获取当前页面url网址信息
    /touch滑屏事件
    监听 手机back键和顶部的回退
  • 原文地址:https://www.cnblogs.com/Phoebe815/p/4101413.html
Copyright © 2011-2022 走看看