88 Merge Sorted Array
class Solution:
def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
"""
Do not return anything, modify nums1 in-place instead.
"""
nums1[m:] = nums2
nums1.sort()
把数组二加入到数组一,然后使用sort排序。
912 Sort an Array
冒泡排序
def bubblesort(self, list):
if len(list) <= 1:
return list
for i in range(len(list) - 1):
flag = False
for j in range(len(list) - i - 1):
if list[j] > list[j + 1]:
list[j], list[j + 1] = list[j + 1], list[j]
flag = True
if not flag:
break
return list
插入排序
def insertionsort(self, list):
if len(list) <= 1:
return list
for i in range(1, len(list)):
a = list[i]
j = i - 1
for j in range(i-1, -2, -1):
if list[j] > a:
list[j+1] = list[j]
else:
break
list[j+1] = a
return list
选择排序
def selectionsort(self, list):
if len(list) <= 1:
return list
for i in range(len(list)-1):
min = i
for j in range(i+1, len(list)):
if list[j] < list[min]:
min = j
if i != min:
list[i], list[min] = list[min], list[i]
return list
可以使用上述三种排序方式,但在leetcode的这题提交时会出现超时问题。
147 Insertion Sort List
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def insertionSortList(self, head: ListNode) -> ListNode:
if head is None or head.next is None:
return head
dummynode = ListNode(0)
cur = head
while cur:
temp = cur.next
pos = dummynode
while pos.next and pos.next.val<cur.val:
pos = pos.next
cur.next = pos.next
pos.next = cur
cur = temp
return dummynode.next
插入排序,取出剩余链表的第一个元素,在已排序序列中插入到合适位置
148 Sort List
class Solution:
def sortList(self, head: ListNode) -> ListNode:
if head is None:
return None
val_list = []
while head:
val_list.append(head.val)
head = head.next
val_list.sort()
ptr = ListNode(val_list.pop())
while len(val_list)!=0:
x = val_list.pop()
new_node = ListNode(x)
new_node.next = ptr
ptr = new_node
return ptr