This question was not understood at the beginning, so please reiterate the requirements of the question:
Given a list of nums, we jump back from the 0th element,
the longest distance we can jump to at the beginning is nums [0],
that is, we can choose to jump to
{1,2, ... , nums [0]},
then, assuming we jumped to a, we can continue to jump. The
optional jump range is {a + 1,…, a + nums [a]}
Jump like this until we jump to the end ,
If this can jump to the end, we return true, otherwise return false
Sort out the idea: this can be solved with a greedy algorithm.
We hope to jump to the farthest place after each jump.
Therefore, we first calculate the farthest position
that can be jumped from each position because each of the nums The meaning of the elements is the farthest distance
that can be jumped from here, and the farthest position that can be reached from nums [i] can be expressed as i + nums [i].
Therefore, we first calculate
nums = for each element of nums = [i + nums [i] for i, value in enumerate (nums)]
Now the meaning of the i-th element in nums is that if we jump from the i-th position,
we can jump to the farthest position.
Our jumping strategy is
Starting from nums [0], jump to the farthest position that can be
reached every time. For example, for nums = [3,2,1,0,4], after calculation, nums = [3,3,3,3,8]
then we can jump from the first position to 0, 2, 3
we have chosen nums [1: 4] That nums [1], nums [2 ], nums [3] the biggest
has been so jump until the last
Either jump to the last position: True
or stuck in a position (that is, the tempmax position that can be reached has not yet reached the end and this value remains unchanged after two consecutive jumps): False
class Solution:
def canJump(self, nums: List[int]) -> bool:
length = len(nums)
nums = [nums[i] + i for i in range(length)]
start = 0
last = 0
this = 0
while this < length - 1:#还没到
if start == 1 and this == last:
return False
elif start == 0:
start = 1
end = nums[this]
if end >= length - 1:
return True
templist = nums[last:end+1]#last+1
tempmax = max(templist)
last = this
this = tempmax
print(last,this)
if this == end and this < length - 1:
return False
return True