1. 程式人生 > >leetcode sort-list

leetcode sort-list

空間 amp arr ast 排序 pub code true 歸並

題目描述

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