【编程题】给出一个非负整数数组,你最初定位在数组的第一个位置,数组中的每个元素的值代表你在那个位置可以跳跃的最大长度。判断你是否能到达数组的最后一个位置。
例如:A = [2,3,1,1,4],返回 true
A = [3,2,1,0,4],返回 false
public class Main3 { /*给出一个非负整数数组,你最初定位在数组的第一个位置,数组中的每个元素的值代表你在那个位置可以跳跃的最大长度。判断你是否能到达数组的最后一个位置。 例如:A = [2,3,1,1,4],返回 true A = [3,2,1,0,4],返回 false*/ //思路:如果数组里没有0,肯定可以 //2、如果存在0,只要0之前的位置上存在可以跳过0位置的点也可以到达 private boolean isTrue(int[] steps){ if(steps == null || steps.length == 0) return false; if(steps[0] == 0) return false; int n = steps.length; Queue<Integer> queue = new LinkedList<>(); for(int i = 0; i < n; i++){ if(steps[i] == 0){ queue.offer(i); } } int idx = -1; while(!queue.isEmpty() && queue.peek() != idx){//如果相等说明是上次循环过的 idx = queue.peek(); for(int i = 0; i < idx; i++){ if(i + steps[i] > idx){ queue.poll(); break; } } } return queue.isEmpty(); } public static void main(String[] args) { int []array = new int[]{3,2,1,0,4}; Main3 main3 = new Main3(); boolean res = main3.isTrue(array); System.out.println(res); } }
/** * 给定一个非负整数数组,你最初位于数组的第一个位置。 * 数组中的每个元素代表你在该位置可以跳跃的最大长度。 * 判断你是否能够到达最后一个位置。 * * 思路:maxIndex ——— 表示从当前位置所能跳到的最远位置的下标 * num[i] ——— 表示i位置所能跳的最远距离 * nums[i]+i ——— 表示i位置左边的距离加上i位置往右能跳的最远距离,即i位置跳完最远距离后所处位置的下标 * num[i]+i 可能会小于maxIndex ,所以需要Math.max,比如 100,1,0,0 * if (maxIndex < i) 表示前面i-1部分所能跳到的最远位置的下标小于i,意思是没能跳到i位置,此时就无法继续往后跳了 */ public class LC55 { public boolean canJump(int[] nums) { int maxIndex = 0; for (int i = 0; i < nums.length; i++) { if (maxIndex < i) { return false; } maxIndex = Math.max(nums[i] + i, maxIndex); } return true; } }
public class Main{ public static void main(String[] args) { int []array = new int[]{3,2,1,0,4}; System.out.println(judge(array)); } private static boolean judge(int[] array) { // TODO Auto-generated method stub int flag = 0; while(flag < array.length){ //System.out.println("this"); if(flag+array[flag] == array.length-1) return true; else{ if(array[flag]==0) //如果是0不可能达到 return false; flag += array[flag]; System.out.println("flag:"+flag); } } return false; } }
class Solution { public: //n是数组长度 bool canJump(int A[], int n) { //当数组为空时 if(n==0) return false; //只有一个元素时直接符合要求 if(n==1) return true; //多个元素的情况 int i=0; while(i<n){ //若跳跃过程中某个元素恰好是0则无法再继续移动 if (!A[i]) return false; //判定是否越界 if(A[i]+i<n-1) i+=A[i]; else if(A[i]+i>=n-1) return true; else return false; } } };
public boolean s (int[] a){ Stack<Integer> stack = new Stack<>(); for(int i=0;i<a.length;i++){ if(a[i] == 0) stack.push(i); } if(stack.isEmpty()) return true; int flag = 0; int size = stack.size(); while (!stack.isEmpty()){ int k = stack.pop(); for(int i=0;i<k;i++){ if(a[i] > k-i){ flag++; break; } } } if(flag<size) return false; return true; }
```
// 总感觉参考答案错了,不知道是不是我理解题目错,如果有错,还望网友指出来
public static boolean test(int[] array){
// 边缘
int edge=array.length-1;
// 标志
int flag=0;
while (flag<edge){
// 为0说明站的原地不能跳
if (array[flag]==0){
return false;
}
flag=array[flag]+flag;
if (flag==edge){
return true;
}
}
return false;
}
```