1. 程式人生 > >109. 排序鏈表

109. 排序鏈表

-o color white robot car word append tab tlist

109. 排序鏈表

解題思路

常數集空間復雜度:將其轉化為數組;

時間復雜度為O(nlogn):用歸並排序;

實現

# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None

class Solution(object):
def sortList(self, head):
"""
:type head: ListNode
:rtype: ListNode

"""
if not head:
return None

# 轉化為數組
result = []
head_tmp = head
while head_tmp:
result.append(head_tmp.val)
head_tmp = head_tmp.next

# 歸並排序
result = self.merge_sort(result)
# 將排序後的結果重新填充到鏈表中
head_tmp
= head

for i in range(len(result)):
head_tmp.val = result[i]
head_tmp = head_tmp.next

return head

def merge(self, left, right):
i, j = 0, 0
left_len, right_len = len(left), len(right)
result = []
while i < left_len and
j < right_len:

if left[i] < right[j]:
result.append(left[i])
i += 1
else:
result.append(right[j])
j += 1
result += left[i:]
result += right[j:]
return result

def merge_sort(self, lists):
lists_len = len(lists)
if lists_len <= 1:
return lists

center = lists_len / 2
left = self.merge_sort(lists[:center])
right = self.merge_sort(lists[center:])
return self.merge(left, right)

109. 排序鏈表