The meaning of problems: From the array index 0 is, stored in the array is the number of steps can jump at the current index, as arr [0] = 2, 0 represents the index from the index 1 and 2 can reach. Finally, ask if you can reach the final index.
Ideas: The reach: recording a position farthest from the current position that can be reached (counting from 0) takes the maximum value can reach every arrival.
class Solution { public : BOOL canJump (Vector < int > & the nums) { IF (nums.size () < 2 ) return to true ; int REACH = 0 ; // REACH: recording from the current position to reach the farthest position for ( int I = 0 ; I <= REACH && I <nums.size (); ++ I) { REACH = max (REACH, I + the nums [I]); IF (REACH> = nums.size () - . 1 ) // to reach the tail return to true ; } return false; } };
Meaning of the questions: Returns the minimum number of steps to reach the final position.
class Solution { public: int jump(vector<int>& nums) { if(nums.empty() || nums.size() <=1) return 0; //cur_max : 当前位置所能到达的最远位置,next_max: 下一步所能到达的最远位置 int cur_max = 0, next_max = 0, step = 0, index = 0; while(index <= cur_max){ while(index <= cur_max){ //计算每一步中所能达到的最大位置 next_max = max(next_max, index+nums[index]); index ++; } cur_max = next_max; step ++; if(cur_max >= nums.size()-1) return step; } return 0; } };