- Question:
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]
, returntrue
.A =
[3,2,1,0,4]
, returnfalse
.
- Analysis:
有题目可知,每一层最多可以条A[i]步,也可以跳0步或者是1步。如果可以到达最高层,就说明中间的每一层都可以到达,所以我们可以使用贪心算法。
- Code:
class Solution { public: bool canJump(vector<int>& nums) { int reach = 1; for (int i = 0;i<reach && reach < nums.size();i++) { reach = max(reach,i+1+nums[i]); } return reach >= nums.size(); } };