diff --git a/problems/0151.翻转字符串里的单词.md b/problems/0151.翻转字符串里的单词.md index 34b099a2..b6b34be3 100644 --- a/problems/0151.翻转字符串里的单词.md +++ b/problems/0151.翻转字符串里的单词.md @@ -467,6 +467,13 @@ class Solution: # 将列表转换成字符串 return " ".join(words) ``` +(版本三) 拆分字符串 + 反转列表 +```python +class Solution: + def reverseWords(self, s): + words = s.split() #type(words) --- list + words = words[::-1] # 反转单词 + return ' '.join(words) #列表转换成字符串 ### Go: diff --git a/problems/0455.分发饼干.md b/problems/0455.分发饼干.md index 91ed40b4..9f59d3ad 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 5c1b9c43..9ec51524 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 diff --git a/problems/0977.有序数组的平方.md b/problems/0977.有序数组的平方.md index d23f948d..b10620d0 100644 --- a/problems/0977.有序数组的平方.md +++ b/problems/0977.有序数组的平方.md @@ -178,6 +178,24 @@ class Solution: return sorted(x*x for x in nums) ``` +```Python +(版本四) 双指针+ 反转列表 +class Solution: + def sortedSquares(self, nums: List[int]) -> List[int]: + #根据list的先进排序在先原则 + #将nums的平方按从大到小的顺序添加进新的list + #最后反转list + new_list = [] + left, right = 0 , len(nums) -1 + while left <= right: + if abs(nums[left]) <= abs(nums[right]): + new_list.append(nums[right] ** 2) + right -= 1 + else: + new_list.append(nums[left] ** 2) + left += 1 + return new_list[::-1] + ### Go: ```Go diff --git a/problems/kamacoder/0055.右旋字符串.md b/problems/kamacoder/0055.右旋字符串.md index 4dea19a8..7d86465f 100644 --- a/problems/kamacoder/0055.右旋字符串.md +++ b/problems/kamacoder/0055.右旋字符串.md @@ -222,6 +222,13 @@ s = s[len(s)-k:] + s[:len(s)-k] print(s) ``` +```Python 切片法 +k = int(input()) +s = input() + +print(s[-k:] + s[:-k]) +``` + ### Go: ```go package main