一、贪心算法:
1.一般解题算法:
①将问题分解为若干个子问题
②找出适合的贪心策略
③求解每一个子问题的最优解
④将局部最优解堆叠成全局最优解
二、刷题:
1.leetcode题目 455 分发饼干(easy):
题目描述:
假设你是一位很棒的家长,想要给你的孩子们一些小饼干。但是,每个孩子最多只能给一块饼干。
对每个孩子 i
,都有一个胃口值 g[i]
,这是能让孩子们满足胃口的饼干的最小尺寸;并且每块饼干 j
,都有一个尺寸 s[j]
。如果 s[j] >= g[i]
,我们可以将这个饼干 j
分配给孩子 i
,这个孩子会得到满足。你的目标是尽可能满足越多数量的孩子,并输出这个最大数值。
思路:贪心+双指针
解决:
class Solution:
def findContentChildren(self, g: List[int], s: List[int]) -> int:
m = len(g)
n = len(s)
g.sort()
s.sort()
i = j = count = 0
while i<m and j<n:
while j<n and g[i]>s[j]:
j += 1
if j < n and g[i]<=s[j]:
count += 1
i += 1
j += 1
return count
2.leetcode题目 376 摆动序列(medium):
解决:
①贪心算法
class Solution:
def wiggleMaxLength(self, nums: List[int]) -> int:
l = len(nums)
if l < 2:
return l
prediff = nums[1] - nums[0]
count = 2 if prediff !=0 else 1
for i in range(2,l):
num_diff = nums[i] - nums[i-1]
if (num_diff>0 and prediff<=0) or (num_diff<0 and prediff>=0):
count += 1
prediff = num_diff
return count
二、继续学习堆栈:
1.leetcode题目 20 有效括号(easy):
题目描述:
解决:(注意if条件 和最后的返回值)
class Solution:
def isValid(self, s: str) -> bool:
a = {')':'(','}':'{',']':'['}
stack = list()
for i in s:
if i in a:
if not stack or stack[-1] != a[i] :
return False
stack.pop()
else:
stack.append(i)
return not stack
2.leetcode题目 1047 删除字符串中的所有相邻重复项(easy):
题目描述:1047. 删除字符串中的所有相邻重复项 - 力扣(LeetCode)
解决:
class Solution:
def removeDuplicates(self, s: str) -> str:
stack = list()
for i in s:
if stack and i == stack[-1]:
stack.pop()
else:
stack.append(i)
return ''.join(stack)
3.leetcode题目 150逆波兰表达式求值(medium):
题目描述:150. 逆波兰表达式求值 - 力扣(LeetCode)
解决:
class Solution:
def evalRPN(self, tokens: List[str]) -> int:
stack = list()
yunsuan = {
"+": add,
"-": sub,
"*": mul,
"/": lambda x, y: int(x / y),
}
for i in tokens:
if i not in "+-*/":
stack.append(int(i))
else:
a = stack.pop()
b = stack.pop()
num = yunsuan[i](b,a)
stack.append(num)
return stack[0]
注意:python中的除法用法 与题目中的不一致。