[Leetcode] 55. Jump Game Java

Source: Internet
Author: User

Topic:

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 .

test instructions and analysis: according to the requirements of the topic, each element in the array represents the furthest distance that can be jumped out from that position, asking whether the last element of the array, starting with the first element (index=0), can be reached, and the last element is considered to be the end point . Here is the arrival, description over also line, see can better understand test instructions.

So here you can use the greedy algorithm, calculate the maximum distance that a point can jump out (the current maximum value and the maximum distance from the current point + can jump), if the maximum distance can jump out of the position of the last point, then return true, can reach, if you reach the current point, you cannot jump backwards, Then the last point cannot be reached and false is returned.

Code:

public class Solution {public    Boolean canjump (int[] nums) {         if (nums.length<1)        return false;        if (nums.length==1)        return true;                int max=0;//The maximum position that can be reached when recording to the current point for        (int i=0;i<nums.length-1;i++) {        Max=math.max (max, i+nums[i]);        if (max<i+1) {//If the next point is not reached (usually the current point is 0, the front can reach the maximum point of the current point or the point at the front of the current point), return false        //System.out.println (false);        return false;        }        if (max>= (nums.length-1)) {        //System.out.println (TRUE);        return true;        }        }        return false;    }}

  

[Leetcode] 55. Jump Game 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.