鍊錶 排序鍊錶(leetcode 148

2022-07-30 10:03:11 字數 958 閱讀 6682

在 o(n log n) 時間複雜度和常數級空間複雜度下,對鍊錶進行排序。

以下解析來自於

常見排序方法有很多,插入排序,選擇排序,堆排序,快速排序,氣泡排序,歸併排序,桶排序等等。。它們的時間複雜度不盡相同,而這裡題目限定了時間必須為o(nlgn),符合要求只有快速排序,歸併排序,堆排序

所以說,本題 =leetcode 876(找中間結點) + leetcode 21(合併兩個有序鍊錶),注意真正實現排序的部分其實是在合併這個部分中。

注意遞迴的終止條件一定要寫對

public class solution148 

listnode fast = head;

listnode slow = head;

listnode pre = head;

while (fast != null && fast.next != null)

pre.next = null;

return merge(sortlist(head), sortlist(slow));

// while (fast.next != null && fast.next.next != null)

// listnode newhead = slow.next;

// slow.next = null;

//// return merge(sortlist(head), sortlist(newhead));

}public listnode merge(listnode l1, listnode l2)else

temp = temp.next;

}temp.next = l1 == null ? l2 : l1;

return dummy.next;

}}

leetcode 鍊錶排序

對鍊錶排序,用歸併排序。題目要求空間時間複雜度為o nlogn 但是空間複雜度為o 1 1.自己寫的程式,時間複雜度為o nlogn 但是空間複雜度為o n 用快慢指標 分別走2步和1步 找到中間節點。但是最後排序的部分,用複製將排好序的部分貼上會原來鍊錶中,這個方法比較笨,而且增加空間複雜度,並不...

leetcode 鍊錶 排序

思路 使用歸併排序。拆分 合併均採用遞迴方式。public listnode sortlist listnode head pre.next null return merge sortlist head sortlist slow public listnode merge listnode l1...

leetcode 排序鍊錶

利用歸併排序的思想,不過這裡排序的不是列表,是乙個鍊錶。具體 如下 definition for singly linked list.class listnode object def init self,x self.val x self.next none class solution obj...