給出一個非負整數數組,你最初定位在數組的第一個位置,數組中的每個元素的值代表你在那個位置可以跳躍的最大長度。判斷你是否能到達數組的最後一個位置。

【編程題】給出一個非負整數數組,你最初定位在數組的第一個位置,數組中的每個元素的值代表你在那個位置可以跳躍的最大長度。判斷你是否能到達數組的最後一個位置。

例如: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));
	}
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章