码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode sort-list

时间:2017-08-27 12:52:56      阅读:216      评论:0      收藏:0      [点我收藏+]

标签:sub   ini   pac   port   复杂度   time   node   tle   imp   

题目描述

 

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

 

思路:时间复杂度为O(nlogn),空间复杂度为常数,用归并排序

在下的代码 时间1162ms 空间27696k

/**
 * Definition for singly-linked list.
 * class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
import java.util.ArrayList;

public class Solution {
    public ListNode sortList(ListNode head) {
        if(head==null||head.next==null){
            return head;
        }
        
    	ListNode mid = findMid(head);
        ListNode midNext = mid.next;
        mid.next = null;
        
        return mergeList(sortList(head), sortList(midNext));
    }
    
    private ListNode mergeList(ListNode list1, ListNode list2) { 
        ListNode head = new ListNode(0);
        ListNode cur = head;
        
        while (list1 != null && list2 != null) {
            if (list1.val <= list2.val){
                cur.next = list1;
                
                list1 = list1.next;
            }
            else {
                cur.next = list2;
                list2 = list2.next;
            }
            cur = cur.next;
        }
        
        if (list1 != null) {
            cur.next = list1;
        }
        else if (list2 != null) {
            cur.next = list2;
        }
        
        return head.next;
    }
    
    private ListNode findMid(ListNode head){
        if (head == null)
            return head;
        
        ListNode fast = head;
        ListNode slow = head;
        
        while (fast.next != null && fast.next.next != null) {
            fast = fast.next.next;
            slow = slow.next;
        }
        
        return slow;
    }
}

  

leetcode sort-list

标签:sub   ini   pac   port   复杂度   time   node   tle   imp   

原文地址:http://www.cnblogs.com/Melinni/p/7440013.html

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