您的位置:首页 > 其它

[Leetcode]Insertion Sort List

2014-12-29 14:24 330 查看
Sort a linked list using insertion sort.

在链表上实现插入排序~  插入排序就是每次循环把一个元素插入到当前排好的结果中相对应的位置,经过n次迭代之后就得到排好序的结果,时间复杂度为O(n^2)~
  自己写的TLE(超时)了,看到也有很多人反映同样的代码,用python写会超时,用java就accept了~  参照了网上的python代码,accept了

class Solution:
# @param head, a ListNode
# @return a ListNode
def insertionSortList(self, head):
pre = cur = dummy = ListNode(0)
dummy.next = head
while cur.next:
if pre.next.val > cur.next.val:
pre = dummy
while pre.next.val < cur.next.val:
pre = pre.next
if pre != cur:
node = cur.next
cur.next = node.next
node.next = pre.next
pre.next = node
else:
cur = cur.next
return dummy.next
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: