mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-06 23:28:29 +08:00
@ -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:
|
||||
|
||||
|
@ -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 {
|
||||
|
@ -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
|
||||
|
||||
|
@ -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
|
||||
|
@ -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
|
||||
|
Reference in New Issue
Block a user