[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
在链表上实现插入排序~ 插入排序就是每次循环把一个元素插入到当前排好的结果中相对应的位置,经过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
相关文章推荐
- leetcode insertion-sort-list
- leetcode之Insertion Sort List
- 【LeetCode】Insertion Sort List
- leetcode题目解答---Insertion Sort List
- LeetCode :: Insertion Sort List [具体分析]
- leetcode之Insertion Sort List
- LeetCode Insertion Sort List
- The Solution to LeetCode 147 Insertion Sort List
- Leetcode[147]-Insertion Sort List
- leetcode-Insertion Sort List
- 【Leetcode】Insertion Sort List (Sorting)
- 【LeetCode】Insertion Sort List 解题报告
- LeetCode - Insertion Sort List
- LeetCode 147:Insertion Sort List
- Leetcode习题:Insertion Sort List
- Leetcode---Insertion Sort List
- [LeetCode-Algorithms-147] "Insertion Sort List" (2017.12.21-WEEK16)
- Leetcode Insertion Sort List
- 【leetcode】 Insertion_Sort_List
- LeetCode - Insertion Sort List