leetcode Jump Game题解

题目描述:

Given an array of non-negative integers, you are initially positioned at the first index of the array.

Each element in the array represents your maximum jump length at that position.

Determine if you are able to reach the last index.

Example 1:

Input: [2,3,1,1,4]
Output: true
Explanation: Jump 1 step from index 0 to 1, then 3 steps to the last index.

Example 2:

Input: [3,2,1,0,4]
Output: false
Explanation: You will always arrive at index 3 no matter what. Its maximum
             jump length is 0, which makes it impossible to reach the last index.

中文理解:

给定一个数组,每个元素代表在该位置所能走的最大步数,判断从数组下标0开始,是否可以到达数组的最后,这个里面有一个误解,就是只要能够走到或者超过数组下标就好了,不需要严格走到数组长度减一的位置。

解题思路:

使用贪心算法,只是关注能够走到的最远的距离,所以可以使用贪心算法来实现。

代码(java):

class Solution {
    public boolean canJump(int[] nums) {
        int position=0;
        for(int i=0;i<nums.length;i++){
            if(position<i || position>=nums.length-1)break;
            position=Math.max(position,i+nums[i]);
        }
        return position>=nums.length-1;
    }
}

猜你喜欢

转载自blog.csdn.net/leo_weile/article/details/90168959