55. Jump Game
Given an array of non-negative integers, you are initially positioned at the first index of the array.
Each element in the array represents your maximum jump length at that position.
Determine if you are able to reach the last index.
Input: [2,3,1,1,4]
Output: true
Explanation: Jump 1 step from index 0 to 1, then 3 steps to the last index.
Example2
Input: [3,2,1,0,4]
Output: false
Explanation: You will always arrive at index 3 no matter what. Its maximum
jump length is 0, which makes it impossible to reach the last index.
难度系数
Medium
解法:每到一个节点,计算当前所能走的最远距离;
class Solution { public: bool canJump(vector<int>& nums) { int size = nums.size(); int step = nums[0]; for (int i = 1; i<size; ++i){ step--; //如果以下条件成立,则i-1的位置必然为0 if (step<0) return false; //nums[i]表示当前位置可以向前走的距离 //step表示到达i时,还能向前走多远; //最后选两者较大的指,就是当前位置能向前走的最远的距离 if (nums[i]>step) step = nums[i]; //运行到这,最远的距离就是i+step,已经包含了之前所有能走的最远距离 } return true; } };