LeetCode55 jumping game (greedy)

Title description

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 whether you can reach the last position.

Example 1:

输入: [2,3,1,1,4]
输出: true
解释: 我们可以先跳 1 步,从位置 0 到达 位置 1, 然后再从位置 13 步到达最后一个位置。

Example 2:

输入: [3,2,1,0,4]
输出: false
解释: 无论怎样,你总会到达索引为 3 的位置。但该位置的最大跳跃长度是 0 , 所以你永远不可能到达最后一个位置。

Algorithm idea plus ac code

The current maximum number of steps for each jump, maxstep records, if the current position i is greater than the current position reached, it means that the current position i cannot be reached, otherwise, the position i can be reached, and the value of arrive is updated at the same time

class Solution {
    
    
public:    
bool canJump(vector<int>& nums) {
    
    
	int maxstep= 0;
	int arrive = 0;
	for(int i = 0; i < nums.size(); i++) {
    
    
	    maxstep = max(i + nums[i], maxstep);
	    if(i > arrive) 
	    {
    
     
	      return false; 
	    }
	    else 
	    {
    
     
	      arrive = maxstep;
	    }
	}
	return true;              
    }
};

Insert picture description here
Execution time is 12ms, memory consumption is 13MB

Guess you like

Origin blog.csdn.net/weixin_44925547/article/details/106260770