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.
For example:
A = [2,3,1,1,4]
, return true
.
A = [3,2,1,0,4]
, return false
.
Subscribe to see which companies asked this question
Show Tags Have you met this question in a real interview? Yes No Discuss#include#include using std::vector; using std::max_element; class Solution { public: bool canJump(vector & nums) { const vector ::size_type SIZE = nums.size(); const vector ::size_type LastIndex = SIZE - 1; // for (vector ::size_type Index = 0; Index < SIZE; ++Index) { nums[Index] += Index; } vector ::iterator Now = nums.begin(); while (Now != nums.end()) { if (*Now >= LastIndex) { return true; } if (Now == nums.begin() + *Now) { return false; } Now = max_element(Now + 1, nums.begin() + *Now + 1); } return true; } };