【编程题】给出一个非负整数数组,你最初定位在数组的第一个位置,数组中的每个元素的值代表你在那个位置可以跳跃的最大长度。判断你是否能到达数组的最后一个位置。
例如:A = [2,3,1,1,4],返回 true
A = [3,2,1,0,4],返回 false
基本思路:0很危险,必须通过前驱点跳过值为0的位置,所以不妨把值为0的下标全部进行入栈操作,然后弹出进行依次处理。
package test_420;
import java.util.Stack;
public class Solution {
public static boolean s (int[] a){
Stack<Integer> stack =new Stack<>();
for(int i=0;i<a.length;i++) {
if(a[i]==0) {
stack.push(i);//是0的下标压入栈
}
}
while(!stack.isEmpty()) {
//3和4号下标在栈中,需要弹出
int index=stack.pop();
//寻找前驱是否能满足条件
if(!search(a,index)) {
return false;
}
}
return true;
}
private static boolean search(int[] a, int index) {
// TODO Auto-generated method stub
for(int i=0;i<index;i++) {
if(a[i]>index-i) {
return true;
}
}
return false;
}
public static void main(String[] args) {
int[] array= {3,2,1,0,4};
System.out.println(s(array));
}
}