您的位置:首页 > 其它

LeetCode: Sort List 解题报告

2014-11-29 20:55 543 查看
[b]Sort List[/b]

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

使用Merge Sort, 空间复杂度是 O(logN) 因为使用了栈空间。

/*
The Solution 2:
Quick Sort.
*/
public ListNode sortList(ListNode head) {
if (head == null) {
return null;
}

// Sort the list from 0 to len - 1
return quickSort(head);
}

// The quick sort algorithm

// All the elements are the same!
public boolean isDuplicate(ListNode head) {
while (head != null) {
if (head.next != null && head.next.val != head.val) {
return false;
}

head = head.next;
}

return true;
}

public ListNode quickSort(ListNode head) {
if (head == null) {
return null;
}

// 如果整个链是重复的,直接跳过。
if (isDuplicate(head)) {
return head;
}

// Use the head node to be the pivot.
ListNode headNew = partition(head, head.val);

// Find the pre position of the pivoit.
ListNode cur = headNew;

ListNode dummy = new ListNode(0);
dummy.next = headNew;

ListNode pre = dummy;

// Find the pre node and the position of the piviot.
while (cur != null) {
if (cur.val == head.val) {
break;
}

// move forward.
cur = cur.next;
pre = pre.next;
}

// Cut the link to be three parts.
pre.next = null;

// Get the left link;
ListNode left = dummy.next;

// Get the right link.
ListNode right = cur.next;
cur.next = null;

// Recurtion to call quick sort to sort left and right link.
left = quickSort(left);
right = quickSort(right);

// Link the three part together.

// Link the first part and the 2nd part.
if (left != null) {
dummy.next = left;

// Find the tail of the left link.
while (left.next != null) {
left = left.next;
}
left.next = cur;
} else {
dummy.next = cur;
}

cur.next = right;

// The new head;
return dummy.next;
}

// Return the new head;
public ListNode partition(ListNode head, int x) {
if (head == null) {
return null;
}

ListNode dummy = new ListNode(0);
dummy.next = head;

ListNode pre = dummy;
ListNode cur = head;

// Record the big list.
ListNode bigDummy = new ListNode(0);
ListNode bigTail = bigDummy;

while (cur != null) {
if (cur.val >= x) {
// Unlink the cur;
pre.next = cur.next;

// Add the cur to the tail of the new link.
bigTail.next = cur;
cur.next = null;

// Refresh the bigTail.
bigTail = cur;

// 移除了一个元素的时候,pre不需要修改,因为cur已经移动到下一个位置了。
} else {
pre = pre.next;
}

cur = pre.next;
}

// Link the Big linklist to the smaller one.
pre.next = bigDummy.next;

return dummy.next;
}


View Code

GITHUB:

https://github.com/yuzhangcmu/LeetCode_algorithm/blob/master/list/SortList.java
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: