冒泡排序
def bubble_sort(list):
for i in range(1, len(list)-1):
for j in range(0, len(list)-i):
if list[j] > list[j+1]:
list[j], list[j+1] = list[j+1], list[j]
return
选择排序
def selection_sort(list):
for i in range(0, len(list)-1):
index = i
for j in range(i, len(list)):
if list[index] > list[j]:
index = j
list[i], list[index] = list[index], list[i]
return
插入排序
def insertion_sort(list):
for i in range(1, len(list)):
index = i
value = list[i]
for j in range(i-1, -1, -1):
if value < list[j]:
index = j
list[j], list[j+1] = list[j+1], list[j]
if index != i:
list[index] = value
快速排序
def quick_sort(list, left, right):
if left < right:
l = left
r = right
index = list[left]
while l < r:
# 从右向左找小的
while l < r and index < list[r]:
r -= 1
if l < r:
list[l] = list[r]
l += 1
# 从左往右找大的
while l < r and index > list[l]:
l += 1
if l < r:
list[r] = list[l]
r -= 1
list[l] = index
quick_sort(list, left, l - 1)
quick_sort(list, l + 1, right)
最大不重复子串
动态规划 记录字母前一次出现位置 dp[i] = temp + 1 if temp < i - front else i - front
def lengthOfLongestSubstring(self, s: str) -> int:
index = {}
temp = res = 0
for i in range(len(s)):
front = index.get(s[i],-1)
index[s[i]] = i
temp = temp + 1 if temp < i - front else i - front
res = max(temp,res)
return res
判定二叉树是否镜像
def isSymmetric(self, root: TreeNode) -> bool:
def isMatch(left: TreeNode,right: TreeNode):
if not left and not right:
return True
if not left or not right or left.val != right.val:
return False
return isMatch(left.left,right.right) and isMatch(left.right,right.left)
return isMatch(root.left,root.right) if root else True
链表倒数K个节点
def getKthFromEnd(self, head: ListNode, k: int) -> ListNode:
first = head
second = head
for i in range(k):
first = first.next
while first:
first = first.next
second = second.next
return second