Given an array of non-negative integers, you is initially positioned at the first index of the array.
Each element of the array represents your maximum jump length is at that position.
Determine if you is able to reach the last index.
for example:
a = [2,3,1,1,4"
, Return true
.
A = [3,2,1,0,4]
, return false
.
The trick with this problem is that each value can jump "value" the size of a step. So our idea is as follows:
1. Record up to now to jump to the farthest distance, recorded as Max
2. Each point can walk the number of steps, recorded as step, and every step forward, step--
3. Determine if the number of steps to jump back after this point is greater than Max, and if it is, update Max, not just go ahead.
In this case, we can see that if the previous point is zero and the step number is not enough for you to pass, then it will automatically bounce back to false. But if you can go all the way to the end, then return True
Package Testandfun;public class Jumpgame {public static void main (String args[]) {int[] A = {3,0,0,0};jumpgame JP = new Jum Pgame (); if (Jp.canjump (A)) System.out.println ("We win"), Else System.out.println ("we Lose");} public boolean canjump (int[] A) { int max = 0; int step = 1; if (a.length<=1) return true; if (a[0]==0&&a.length>1) return false; for (int i=0;i<a.length;i++) { step--; if (I+a[i]>max) { max = i+a[i]; Step = A[i]; } if (step==0 && i<a.length-1) return false; } return true;} }
"Leetcode" Classic jump Game in JAVA