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

    nlogn对于LIST来说只能是merge sort了。
    quick sort没法倒退,不适用于singly list。

    length < 3 手动排序
    length >= 3,找到中间,前后分别排序,再merge,其实就是典型的merge sort + node management.

    public class Solution 
    {
        public ListNode sortList(ListNode head) 
        {
            if(head == null || head.next == null) return head;
            if(head.next.next == null)
            {
                if(head.val > head.next.val)
                {
                    ListNode res = head.next;
                    res.next = head;
                    head.next = null;
                    return res;
                }
                else return head;
            }
            ListNode slow = head;
            ListNode fast = head;
    
            while(fast.next != null && fast.next.next != null)
            {
                slow = slow.next;
                fast = fast.next.next;
            }
            fast = slow.next;
            slow.next = null;
            
            ListNode left = sortList(head);
            ListNode right = sortList(fast);
            ListNode dummy = new ListNode(-1);
            ListNode res = dummy;
            slow = left;
            fast = right;
            while(slow!=null && fast!=null)
            {
                if(slow.val < fast.val)
                {
                    res.next = slow;
                    res = res.next;
                    slow = slow.next;
                }
                else
                {
                    res.next = fast;
                    res = res.next;
                    fast = fast.next;
                }
            }
            if(slow == null) res.next = fast;
            else res.next = slow;
            
            return dummy.next;
            
        }
        
    
    }
    

    写的很垃圾,怎么快怎么来。。slow fast反复当做pointer使用。。

  • 相关阅读:
    H5学习的第三周
    2017.3.12 H5学习的第一周
    js中比较实用的函数用法
    JS学习中遇到的一些题目
    H5学习第四周
    idea快捷键
    中国国内可用API合集
    ssm整合 idea+maven版
    Dubbo的使用及原理浅析
    $.extend 和$.fn.extend的区别
  • 原文地址:https://www.cnblogs.com/reboot329/p/5867740.html
Copyright © 2011-2022 走看看