贪心2
2019-12-31 本文已影响0人
Arsenal4ever
demo4a:跳跃游戏(medium)----(贪心)
来源:leetcode 55
思路:找第一步能跳跃到的最远位置,在接着往下一个元素找能到的最远位置,维护能到达的最远位置,判断步数与能到达最远位置的关系。
class Solution(object):
def canJump(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
max_position = 0
for i, num in enumerate(nums):
max_position = max(max_position, i+num)
while max_position < len(nums)-1 and i == max_position:
return False
return True
上述代码中到达最大位置那里还可以进行优化!!!
demo4b:跳跃游戏(hard)----(贪心)
来源:leetcode 45
思路:思考能跳到的最远位置和应该跳到的位置,如果能跳到的最远位置上标记的能跳跃到的位置比之前位置上标记的能跳到的最远位置小,则跳到之前的位置,维护跳跃次数。
class Solution(object):
def jump(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if len(nums) == 1:
return 0
max_position = nums[0]
per_max_position = nums[0]
times = 1
for i in range(len(nums)):
if i > max_position:
times += 1
max_position = per_max_position
per_max_position = max(per_max_position, nums[i]+i)
return times
demo5:射击气球(medium)----(排序,贪心)
来源:leetcode 452
思考:做贪心,先枚举。思考如何一箭射穿最多的气球,需要维护什么?什么时候需要增加弓箭手?
class Solution(object):
def findMinArrowShots(self, points):
"""
:type points: List[List[int]]
:rtype: int
"""
if len(points) < 2:
return len(points)
points = sorted(points, key=lambda x: x[0])
shot_start = points[0][0]
shot_end = points[0][1]
times = 1
for start, end in points:
if start > shot_end:
times += 1
shot_end = end
if start > shot_start:
shot_start = start
if end < shot_end:
shot_end = end
return times
demo6:最佳加油方法(hard)----(堆、贪心)
来源:leetcode 134
思路:和demo4b类似。扫描加油站,维护一个油量最大堆,如果到不了下一个加油站,则从最大堆中取出。
思考什么时候该维护最大堆,什么时候只需要维护一个最大值 ----> 如果可叠加,维护堆,如果只能取一个,维护最大值!
待写完堆之后,再来做这道题!!!