python leetcode_leetcode 刷题经验,主力 python
                                                            生活随笔
收集整理的這篇文章主要介紹了
                                python leetcode_leetcode 刷题经验,主力 python
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.                        
                                1. 樹的先序遍歷可以求高度,后序遍歷可以求深度。
劍指 Offer 55 - II. 平衡二叉樹?leetcode-cn.com2. 二叉搜索樹的中序遍歷可以遞增地返回所有元素。逆序的中序遍歷(即先右子節點,再根節點,再左子節點)可以遞減的返回所有元素。
3. python 的字典就是非常好的哈希工具。get 方法可以寫參數當默認值,常用計數 dic.get(ch, 0) + 1
4. 求質數比較快的方法 ,篩法
isPrime = [True] * (n + 1) # 1, 2, ..., nisPrime[1] = Falseidx = 2while idx <= n:if isPrime[idx]:i = idxwhile idx * i <= n:isPrime[idx * i] = Falsei += 1idx += 15. python 快速排序實現可以更簡潔,思路更清楚
class Solution:def quickSort(self, A, left, right):if left < right:pos = self.partition(A, left, right)self.quickSort(A, left, pos-1)self.quickSort(A, pos+1, right)def partition(self, A, left, right):i, j = left, rightwhile i < j:while i < j and A[j] >= A[left]: j -= 1while i < j and A[i] <= A[left]: i += 1A[i], A[j] = A[j], A[i]A[i], A[left] = A[left], A[i]return i6. python 歸并排序
""" def mergeSort(A, left, right):pass def merge(A, left, mid, right): [left, mid] [mid+1, right]pass觀察最外層遞歸 [3, 2, 4, 5, 7, 1, 9]0 1 2 3 4 5 6 left = 0 right = 6, mid = 3, mergeSort(A, 0, 3), mergeSort(A, 4, 6) merge(A, left = 0, mid = 3, right = 6)[2, 3, 4, 5, 1, 7, 9]0 1 2 3 4 5 6 A[left], ..., A[mid] 序列 和 A[mid+1], ..., A[right]觀察最內層遞歸 mergeSort(A, left = 2, right = 3):if left < right: Truemid = 2mergeSort(A, left = 2, mid = 2)mergeSort(A, left = mid + 1 = 3, right = 3)merge(A, left = 2, mid = 2, right = 3) """def mergeSort(A, left, right):if left < right:mid = (left + right) // 2mergeSort(A, left, mid)mergeSort(A, mid+1, right)merge(A, left, mid, right)def merge(A, left, mid, right):i, j = left, mid + 1 # 合并 A[left], ..., A[mid] 序列 和 A[mid+1], ..., A[right] 序列temp = []while i <= mid and j <= right:if A[i] <= A[j]:temp.append(A[i])i += 1else:temp.append(A[j])j += 1while i <= mid:temp.append(A[i])i += 1while j <= right:temp.append(A[j])j += 1for i in range(len(temp)):A[left+i] = temp[i]L = [4,2,1,5,3,2,1] mergeSort(L, 0, len(L)-1)7. python oj 處理標準輸入 What does Python's eval() do?
- 示例1
- 示例2
8. 二叉樹遍歷的迭代算法
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None- 前序遍歷
- 后序遍歷
- 中序遍歷
9. BFS
import collections graph = {"A": ["B", "C"],"B": ["A", "C", "D"],"C": ["A", "B", "D", "E"],"D": ["B", "C", "E", "F"],"E": ["C", "D"],"F": ["D"] }# 最初版本 BFS def BFS(graph, s):queue = collections.deque()queue.append(s)seen = set()seen.add(s)while queue:vertex = queue.popleft()nodes = graph[vertex]for w in nodes:if w not in seen:queue.append(w)seen.add(w)print(vertex)BFS(graph, "A") # ABCDEF print('---------------')# DFS 迭代實現 def DFS(graph, s):stack = []stack.append(s)seen = set()seen.add(s)while stack:vertex = stack.pop()nodes = graph[vertex]for w in nodes:if w not in seen:stack.append(w)seen.add(w)print(vertex) DFS(graph, "A") # ACEDFB# BFS 打印路徑 def BFS(graph, s):queue = collections.deque()queue.append(s)seen = set()seen.add(s)parent = {s: None}while queue:vertex = queue.popleft()nodes = graph[vertex]for w in nodes:if w not in seen:queue.append(w)seen.add(w)parent[w] = vertex# print(vertex)return parentparent = BFS(graph, "A") v = 'F' while v != None:print(v)v = parent[v] # F D B A10. 并查集
# 對于一維輸入 # https://leetcode-cn.com/problems/paths-with-sum-lcci/ class UF:def __init__(self, n):self.rank = [0 for _ in range(n)] # 代表樹的高度,用來將樹平衡self.up = [i for i in range(n)]def find(self, x):if self.up[x] == x:return xelse:self.up[x] = self.find(self.up[x])return self.up[x]def union(self, x1, x2):r1 = self.find(x1)r2 = self.find(x2)if r1 == r2:returnif self.rank[r1] == self.rank[r2]:self.rank[r1] += 1self.up[r2] = r1elif self.rank[r1] > self.rank[r2]:self.up[r2] = r1else:self.up[r1] = r2# 對于二維輸入 # https://leetcode-cn.com/problems/number-of-islands/ class UnionFind:def __init__(self, grid: List[List[str]]):m, n = len(grid), len(grid[0])self.count = 0self.parent = [-1] * (m * n)self.rank = [0] * (m * n)for i in range(m):for j in range(n):if grid[i][j] == "1":self.parent[i * n + j] = i * n + jdef find(self, i):if self.parent[i] != i:self.parent[i] = self.find(self.parent[i])return self.parent[i]def union(self, x, y):rootx = self.find(x)rooty = self.find(y)if rootx != rooty:if self.rank[rootx] < self.rank[rooty]:rootx, rooty = rooty, rootxself.parent[rooty] = rootxif self.rank[rootx] == self.rank[rooty]:self.rank[rootx] += 111. DFS中序遍歷樹結構并時刻比較先后訪問的節點。
注意在什么位置更新上一個訪問的節點 preNode。就是什么時候按照中序遍歷,中間訪問到了新的值,什么時候更新。
# https://leetcode-cn.com/problems/recover-binary-search-tree/solution/zhong-xu-bian-li-by-powcai/ # 恢復二叉樹 class TreeNode:def __init__(self, x):self.val = xself.left = Noneself.right = Noneclass Solution:def __init__():self.preNode = Nonedef InOrderTravalsal(root):if not root:returnInOrderTravalsal(root.left)# 把 root.val 和 self.pre.val 進行一些比較# ...# 就在這更新剛剛 preNode. 因為訪問下一個節點也一定是在遞歸函數的這個位置self.preNode = rootInOrderTravalsal(root.right)總結
以上是生活随笔為你收集整理的python leetcode_leetcode 刷题经验,主力 python的全部內容,希望文章能夠幫你解決所遇到的問題。
 
                            
                        - 上一篇: RegExp类型exec()方法的返回值
- 下一篇: Poj2586 每五个月都是亏
