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

    148. Sort List

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

    Example 1:

    Input: 4->2->1->3
    Output: 1->2->3->4
    

    Example 2:

    Input: -1->5->3->4->0
    Output: -1->0->3->4->5
    题意:链表排序,时间复杂度nlogn
    代码如下:
    /**
     * Definition for singly-linked list.
     * function ListNode(val) {
     *     this.val = val;
     *     this.next = null;
     * }
     */
    /**
     * @param {ListNode} head
     * @return {ListNode}
     */
    // 归并排序
    var sortList = function(head) {
        if(!head || !head.next) return head;
        let pre=head,slow=head,fast=head;
        while(fast && fast.next){
            pre=slow;
            slow=slow.next;
            fast=fast.next.next;
        }
        pre.next=null;
        return merge(sortList(head),sortList(slow));
    };
    var merge=function(l1,l2){
        let node=new ListNode(-1);
        let cur=node;
        while(l1 && l2){
            if(l1.val<l2.val){
                cur.next=l1;
                l1=l1.next;
            }else{
                cur.next=l2;
                l2=l2.next;
            }
            cur=cur.next;
        }
        if(l1) cur.next=l1;
        if(l2) cur.next=l2;
        return node.next;
    }
  • 相关阅读:
    mysql-03
    mysql-02
    mysql-01
    RESTFUL设计风格
    mysql水平拆分和垂直拆分
    redis连环夺命问
    Python 的十大重要特性
    吊打--redis
    python2和3 的区别
    tornado第一段代码
  • 原文地址:https://www.cnblogs.com/xingguozhiming/p/11084897.html
Copyright © 2011-2022 走看看