理论基础
贪心的本质是选择每一阶段的局部最优,从而达到全局最优。
455.分发饼干
- 题目链接:455.分发饼干
class Solution(object):
def findContentChildren(self, g, s):
"""
:type g: List[int]
:type s: List[int]
:rtype: int
"""
g.sort(reverse=True)
s.sort(reverse=True)
count = 0
i=0
for j in range(len(s)):
while i<len(g):
if s[j]>=g[i]:
count+=1
i+=1
break
else:
i=i+1
return count
- 从小到大index版
class Solution(object):
def findContentChildren(self, g, s):
"""
:type g: List[int]
:type s: List[int]
:rtype: int
"""
g.sort()
s.sort()
count = 0
index = len(s)-1
for i in range(len(g)-1, -1, -1):
if index>=0 and s[index]>=g[i]:
count+=1
index-=1
return count
376.摆动序列
- 题目链接:376.摆动序列
class Solution(object):
def wiggleMaxLength(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if len(nums)==1:
return 1
count=1
for i in range(1,len(nums)-1):
print(nums[i]-nums[i-1])
if (nums[i]-nums[i-1])*(nums[i+1]-nums[i])<0:
count+=1
else:
nums[i]=nums[i-1]
if nums[len(nums)-1]-nums[len(nums)-2]!=0:
count+=1
return count
- 这个版本相当于index=0时如果curdiff!=0则计数一次,就不会出现count少1的情况。
- 且curdiff!=0才更新,不满足prediff*curdiff<=0(相当于取子数组)
class Solution(object):
def wiggleMaxLength(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if len(nums)<=1:
return len(nums)
count=1
prediff,curdiff=0,0
for i in range(len(nums)-1):
curdiff=nums[i+1]-nums[i]
if prediff*curdiff<=0 and curdiff!=0:
count+=1
prediff=curdiff
return count
53. 最大子序和
- 题目链接:53. 最大子数组和
- 贪心:当tmp<0时则放弃当前数组,因为后面的数组加上tmp肯定是小于自身和的
- 全负数用例(取最大负数):注意max_sum=最小负数,tmp先加再比较。
class Solution(object):
def maxSubArray(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
max_sum = float('-inf')
tmp = 0
for i in range(len(nums)):
tmp+=nums[i]
if tmp>max_sum:
max_sum =tmp
if tmp<0:
tmp=0
return max_sum