"Leetcode" Classic jump Game in JAVA

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.