Leetcode 148. Sort List
单向链表排序,O(nLog(n))的时间复杂度和常数的空间复杂度。
因为常数的空间复杂度不能另外开数组排序或者链表比较。
O(nLog(n))说明应该用的不是冒泡插入等,可能是归并或者快排。
解法一:归并排序.
class Solution(object):
def sortList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if head == None or head.next == None:
return head
# middleNode = self.getMid(head)
fast, slow =head.next, head
while fast and fast.next:
fast = fast.next.next
slow = slow.next
middleNode = slow.next
slow.next = None # PAY ATTENTION!!
left = self.sortList(head)
right = self.sortList(middleNode)
return self.mergeList(left, right)
#def getMid(self, head):
# f = head
# slow = head
# middle = None
# while(f.next == None):
# middle = slow
# slow = slow.next
# f = f.next.next
# middle = slow.next
# slow.next = None
# return middle
def mergeList(self, l, r):
if not r or not l:
return r or l
tempHead = ListNode(0)
cur = tempHead
while(l != None and r != None):
if(l.val <= r.val):
cur.next = l
cur = cur.next
l = l.next
else:
cur.next = r
cur = cur.next
r = r.next
if (l != None):
cur.next = l
if (r != None):
cur.next = r
return tempHead.next
中间有个步骤可以直接写,不用另外写成函数,注意细节,不然可能会Time Excess.
解法二:快排
参考别人的解法,想法是设置了两个Pivot其中一个记录前一位,这样就不需要双向链表了。