Leetcode [55] (Java): Jump Game

Source: Internet
Author: User
Tags jumping games

title : Jumping Games

Difficulty : Medium

topic content :

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.

translation :

Given a non-negative integer array, you were initially positioned in the first index of the array.

Each element in the array represents the maximum hop length that you have in that position.

Determine if you can reach the last index.

Example 1:

Input: [2,3,1,1,4]output:trueexplanation: First step, jump 2 steps to index 2, Step 1 to index 3, Step 1 step to index 4, reach
First step, jump 1 steps to index 1, Step 3 step to index 4, reach

Example 2:

Input: [3,2,1,0,4]output:falseexplanation: Anyway, you always get to index 3. Its maximum jump length is 0, which makes it impossible to reach the last index.

my train of thought : Do not know how to do ...

Answer code :

1  Public BooleanCanjump (int[] A) {2     intMax = 0;3      for(inti=0;i<a.length;i++){4         if(I>max) {return false;}5max = Math.max (a[i]+I,max);6     }7     return true;8}

The answer : Because the number of steps can be jumped from 0 to a[I], so long as the front can reach the farthest subscript maximum can be greater than the following subscript, it means to jump, or not jump . The farthest subscript to be reached is a[i] + I.

eg.:[3,2,1,0,4]

The first three can reach the farthest subscript maximum value is 3, so at this time the farthest only to subscript 3, and subscript 3 the farthest subscript is their own, to the subscript 4 to judge the farthest subscript than their own subscript smaller, so jump.

Leetcode [55] (Java): Jump Game

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.