题目一
排序,从后往前遍历
class Solution(object): def findContentChildren(self, g, s): g.sort() # 将孩子的贪心因子排序 s.sort() # 将饼干的尺寸排序 index = len(s) - 1 # 饼干数组的下标,从最后一个饼干开始 result = 0 # 满足孩子的数量 for i in range(len(g)-1, -1, -1): # 遍历胃口,从最后一个孩子开始 if index >= 0 and s[index] >= g[i]: # 遍历饼干 result += 1 index -= 1 return result
第二题
class Solution(object):
def wiggleMaxLength(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
pre=0
res=1
cur=0
if len(nums)==1:
return 1
for i in range(len(nums)-1):
cur=nums[i+1]-nums[i]
if (pre<=0 and cur>0) or (pre>=0 and cur<0):
res+=1
pre=cur
return res
- 情况一:上下坡中有平坡(在判断条件中加=号)
- 情况二:数组首尾两端(res初始设为一,pre初始设为0)
- 情况三:单调坡中有平坡(只有在满足条件是,pre=cur)
当cur<0,直接丢弃
先记录,后丢弃(顺序不能反,反了之后如果都是负的,输出为0)
class Solution(object):
def maxSubArray(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
result=float('-inf')
cur = 0
for i in range(len(nums)):
cur = cur + nums[i]
if cur > result:
result=cur
if cur < 0:
cur = 0
return result