码迷,mamicode.com
首页 > Web开发 > 详细

148. Sort List(js)

时间:2019-06-25 19:47:19      阅读:154      评论:0      收藏:0      [点我收藏+]

标签:complex   com   @param   node   UNC   sort list   rtl   tput   constant   

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;
}

 

148. Sort List(js)

标签:complex   com   @param   node   UNC   sort list   rtl   tput   constant   

原文地址:https://www.cnblogs.com/xingguozhiming/p/11084897.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!