标签: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;
}
}
标签:sub ini pac port 复杂度 time node tle imp
原文地址:http://www.cnblogs.com/Melinni/p/7440013.html