[Algorithm question 8] Jumping game

Source: LeetCode Question 55

Given an array of non-negative integers, you are initially at the first position of the array.

Each element in the array represents the maximum length you can jump at that position.

Determine if you can reach the last position.

Example 1:

Input: [2,3,1,1,4]
output: true
Explanation: Jump 1 step from position 0 to 1, then jump 3 steps to the last position.

Example 2:

Input: [3,2,1,0,4]
output: false
Explanation: No matter what, you will always reach the position at index 3. But the maximum jump length for that position is 0, so you can never get to the last position.

code show as below:

 1 class Solution:
 2     def canJump(self, nums):
 3         """
 4         :type nums: List[int]
 5         :rtype: bool
 6         """
 7         max_reach,last_index=0,len(nums)-1
 8         for i,x in enumerate(nums):
 9             if max_reach<i:
10                 return False
11             if max_reach>=last_index:
12                 return True
13             max_reach=max(max_reach,i+x)

 

Source: LeetCode Question 45

Given an array of non-negative integers, you are initially at the first position of the array.

Each element in the array represents the maximum length you can jump at that position.

Your goal is to get to the last position of the array using the fewest number of jumps.

Example:

Input: [2,3,1,1,4]
Output: 2
Explanation: The minimum number of jumps to jump to the last position is 2.
     Jump from index 0 to index 1,  1 step, then  3 step to the last position in the array.

illustrate:

Assuming you can always reach the last position of the array.

 

 

The idea is as follows:

 

code show as below:

 1 class Solution:
 2     def jump(self, nums):
 3         """
 4         :type nums: List[int]
 5         :rtype: int
 6         """
 7         start=end=step=0
 8         while end<len(nums)-1:
 9             start,end=end+1,max(i+nums[i] for i in range(start,end+1))
10             step+=1
11         return step

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324729929&siteId=291194637