題意
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
解法
貪心解法:
- 在每個點記錄當前可以到達的最大距離reach
- 如果 i > reach,說明到達不了這個點,false
實現
class Solution {
public:
bool canJump(vector<int>& nums) {
if(nums.size() == 0) return false;
if(nums.size() == 1) return true;
int reach = 0;
for(int i = 0; i < nums.size() && i <= reach; ++i){
if(nums[i] + i > reach) reach = nums[i] + i;
}
return reach >= nums.size()-1;
}
};