题目描述:给定一个非负整数数组,你最初位于数组的第一个位置。
数组中的每个元素代表你在该位置可以跳跃的最大长度。
判断你是否能够到达最后一个位置。
题目地址:https://leetcode-cn.com/problems/jump-game/
思路:
1、如果数组里的数字都不为0那么肯定能到达最后一个位置,那么重点看为0的元素的之前元素能否跳过这个0元素,此时分为两种情况,一个是当前0元素在最后一个位置,那么可以直接返回true,一个是当前0元素在其它位置,那么往前循环,而且每循环一次需要多增加一步,满足条件即可跳过这个0元素,否则跳出循环。
2、设置maxPos为当前所能到达的最大位置,如果i在此范围类,则可以继续前进,如果能到达的位置大于maxPos则更新它的值,当i仍在循环且i大于maxPos时可以直接返回false;
代码展示:
1、
/**
* @ClassName Solution
* @Description
* @Author Administrator
* @Date 2020/6/8 11:42
* @Version 1.0
**/
class Solution {
public boolean canJump(int[] nums) {
if(nums == null)
return false;
if(nums.length == 1)
return true;
int i;
for(i = 0; i < nums.length; i++){
if(nums[i] == 0){
int temp;
if(i == nums.length - 1)
return true;
else
temp = 2;
int j;
for(j = i - 1; j >= 0; j--, temp ++){
if(nums[j] >= temp)
break;
}
if(j == -1)
break;
}
}
if(i < nums.length)
return false;
else
return true;
}
}
2、
/**
* @ClassName Solution1
* @Description
* @Author Administrator
* @Date 2020/6/8 12:05
* @Version 1.0
**/
public class Solution1 {
public boolean canJump(int[] nums) {
int maxPos = 0;
for(int i = 0; i < nums.length; i++){
if(i <= maxPos){
if(nums[i] + i > maxPos)
maxPos = nums[i] + i;
}
else
return false;
}
if(maxPos >= nums.length - 1)
return true;
else
return false;
}
}