【計蒜客】跳躍遊戲一
阿新 • • 發佈:2018-12-22
題目描述
給定一個非負整數陣列,假定你的初始位置為陣列第一個下標。陣列中的每個元素代表你在那個位置能夠跳躍的最大長度。
請確認你是否能夠跳躍到陣列的最後一個下標。
例如:A = [2,3,1,1,4]能夠跳躍到最後一個下標,輸出true;
A=[3,2,1,0,4] 不能跳躍到最後一個下標,輸出false。
輸入格式
第一行輸入一個正整數 n(1≤n≤500),接下來的一行 n個整數,輸入陣列 Ai。
輸出格式
如果能跳到最後一個下標,輸出true,否則輸出false。
樣例輸入
5
2 0 2 0 1
樣例輸出
true
AC程式碼
import java.util.Scanner; public class Main { public static void main(String[] args){ Scanner sc = new Scanner(System.in); int len = sc.nextInt(); int[] arr = new int[len]; for(int i = 0; i < len; i++){ arr[i] = sc.nextInt(); } int index = 0; while(true){ index += arr[index]; if(index >= len-1){ System.out.println("true"); break; }else if(arr[index] ==0){ System.out.println("false"); break; } } } }