From 784ed2a68c2eb3a790bda49dc5fbbee797f99fbe Mon Sep 17 00:00:00 2001 From: Henry Zheng <1204831218@qq.com> Date: Mon, 20 May 2024 08:51:59 +0800 Subject: [PATCH] =?UTF-8?q?Update=20#0455=20=E5=88=86=E5=8F=91=E9=A5=BC?= =?UTF-8?q?=E5=B9=B2=20=E6=A0=88=20=E5=A4=A7=E9=A5=BC=E5=B9=B2=E4=BC=98?= =?UTF-8?q?=E5=85=88=20&=20#700=20=E4=BA=8C=E5=8F=89=E6=90=9C=E7=B4=A2?= =?UTF-8?q?=E6=A0=91=E4=B8=AD=E7=9A=84=E6=90=9C=E7=B4=A2=20=E6=A0=88-?= =?UTF-8?q?=E9=81=8D=E5=8E=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0455.分发饼干.md | 20 +++++++++++++++++++- problems/0700.二叉搜索树中的搜索.md | 20 ++++++++++++++++++++ 2 files changed, 39 insertions(+), 1 deletion(-) diff --git a/problems/0455.分发饼干.md b/problems/0455.分发饼干.md index 6ae206db..b6f5bae5 100644 --- a/problems/0455.分发饼干.md +++ b/problems/0455.分发饼干.md @@ -206,8 +206,26 @@ class Solution: ``` -### Go +栈 大饼干优先 +```python +from collecion import deque +class Solution: + def findContentChildren(self, g: List[int], s: List[int]) -> int: + #思路,饼干和孩子按从大到小排序,依次从栈中取出,若满足条件result += 1 否则将饼干栈顶元素重新返回 + result = 0 + queue_g = deque(sorted(g, reverse = True)) + queue_s = deque(sorted(s, reverse = True)) + while queue_g and queue_s: + child = queue_g.popleft() + cookies = queue_s.popleft() + if child <= cookies: + result += 1 + else: + queue_s.appendleft(cookies) + return result +``` +### Go ```golang //排序后,局部最优 func findContentChildren(g []int, s []int) int { diff --git a/problems/0700.二叉搜索树中的搜索.md b/problems/0700.二叉搜索树中的搜索.md index 9efb1e05..58ada3cb 100644 --- a/problems/0700.二叉搜索树中的搜索.md +++ b/problems/0700.二叉搜索树中的搜索.md @@ -262,6 +262,26 @@ class Solution: return None ``` +(方法三) 栈-遍历 +```python +class Solution: + def searchBST(self, root: TreeNode, val: int) -> TreeNode: + stack = [root] + while stack: + node = stack.pop() + # 根据TreeNode的定义 + # node携带有三类信息 node.left/node.right/node.val + # 找到val直接返回node 即是找到了该节点为根的子树 + # 此处node.left/node.right/val的前后顺序可打乱 + if node.val == val: + return node + if node.right: + stack.append(node.right) + if node.left: + stack.append(node.left) + return None +``` + ### Go