Python刷题
春野与望
理想只是一个环的非空子集。
展开
-
NC6 二叉树中的最大路径和(Python 3)
dfs方法class Solution: def maxPathSum(self , root: TreeNode) -> int: sum=float('-inf') def dfs(root): nonlocal sum if not root: return float('-inf') leftsum=dfs(root.left)原创 2021-11-06 00:48:04 · 423 阅读 · 0 评论 -
NC13 二叉树的最大深度(Python3)
dfs方法class Solution: def maxDepth(self , root: TreeNode) -> int: if not root: return 0 return max(self.maxDepth(root.left),self.maxDepth(root.right))+1原创 2021-11-05 00:47:05 · 111 阅读 · 0 评论 -
NC5 二叉树根节点到叶子节点的所有路径和(Python3)
dfs方法class Solution: def sumNumbers(self , root: TreeNode) -> int: def dfs(root,presum): if not root: return 0 #更新这一层的路径值 cursum=presum*10+root.val #判断当前节点是不是叶子节点,如果是,就把这条路径值加到原创 2021-11-03 23:47:49 · 511 阅读 · 0 评论 -
NC7 买卖股票的最好时机(Python3)
class Solution: def maxProfit(self , prices: List[int]) -> int: i=0 min_price=prices[0] min_price_i=0 max_lirun=prices[0]-min_price while i<=len(prices)-1: if prices[i]<min_price:原创 2021-11-03 00:38:16 · 83 阅读 · 0 评论 -
NC4 判断链表中是否有环(Python3)
hash表方法class Solution: def hasCycle(self , head: ListNode) -> bool: nodes=set() while head: if head in nodes: return True else: nodes.add(head) head=head.next原创 2021-11-01 23:18:17 · 82 阅读 · 0 评论 -
NC3 链表中环的入口结点(Python3)
hash表方法class Solution: def EntryNodeOfLoop(self, pHead): #创建hash表存储访问过的结点 nodes=set() #判断有无成环结点 while pHead: if pHead in nodes: #查到了,就返回这个节点 return pHead else:原创 2021-11-01 00:50:52 · 117 阅读 · 0 评论 -
NC2 重排链表(Python3)
class Solution: def reorderList(self , head ): #判断链表是否为空或仅一个节点 if not head or not head.next: return head #使用快慢指针来寻找中间结点 fast=head slow=head while fast and fast.next: slow=slow.next原创 2021-10-30 23:58:25 · 297 阅读 · 0 评论 -
NC1 大数加法(Python3)
class Solution: def solve(self,s,t): res = "" i=len(s)-1 #指针,初始化为s的尾部,即最低位 j=len(t)-1 #指针,初始化为t的尾部,即最低位 carry=0 #表示进位 while i >= 0 or j >= 0: #高位补0 if i>=0: n1=int原创 2021-10-30 01:20:43 · 105 阅读 · 0 评论