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.

For example:
A = [2,3,1,1,4], return true.

A = [3,2,1,0,4], return false.

我们可以用贪心算法来解决。维护一个指针,指针不断的靠近终点,每前进一步指针的值都减1,指针的值根据经过的元素而更新。代码如下:
public class Solution {
    public boolean canJump(int[] nums) {
        if(nums == null || nums.length == 0) return false;
        int cur = nums[0];
        for(int i = 1; i < nums.length; i++) {
            if(cur >= nums.length - 1) return true;
            //每前进一步,cur的值就减1
            cur --;
            if(cur < 0) return false;
            //cur移动到了nums[i]的位置,查看是否更新cur的值
            if(nums[i] > cur) {
                cur = nums[i];
            }
            if(cur == 0 && i < nums.length - 1) return false;
        }
        return true;
    }
}

猜你喜欢

转载自kickcode.iteye.com/blog/2275082