跳躍游戲
https://leetcode.cn/problems/jump-game/description/
題目分析
nums = [2,3,1,1,4]
當前位置array[i]表示基于當前位置可以跳的最大步數(shù), 例如:從當前index=0 位置,可以跳的步數(shù)為1步,2步,跳1步到index=1位置, 跳2步到index=2位置; 繼續(xù)遍歷index = 1 位置, 而index=1 位置是通過index= 0 通過跳1步過來的,對于按最大步數(shù)跳2步來說,index = 1位置是從index= 0 位置必達的,所以,我們只需要維護按照最大步數(shù)跳的最大索引就行;
跳轉的最大索引maxIndex表示為基于當前索引和可以跳轉的最大步數(shù)之和, 當 index = 0 位置,maxIndex = 2,對于index=1 位置,當前可以跳轉的最大索引為maxIndex= 1+3=4,于是,在遍歷的過程中通過動態(tài)維護最大索引,當maxIndex >= array.length-1時,即認為可以跳轉到;
編程實現(xiàn)
public boolean canJump(int[] nums) {
if(nums == null || nums.length <= 0){
return false;
}
int maxIndex = 0;
for(int index = 0; index< nums.length;index++){
if(index <= maxIndex){
if(index + nums[index] > maxIndex){
maxIndex = index + nums[index];
}
if(maxIndex >= nums.length -1){
return true;
}
}
}
return false;
}