【题目】

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

【思路】

贪心、取最大

【代码】

倒序考虑。设flag在尾部,一直考虑前面一步i,nums[i]+i>=flag,那i点可以到达flag点,则flag回跳到i点。

当循环结束,flag跳到起点0,则返回true。

class Solution {
    public boolean canJump(int[] nums) {
        int flag=nums.length-1;
        for(int i=nums.length-1;i>=0;i--){
            if(nums[i]+i>=flag)
                flag=i;
        }
        return flag==0;
    }
}

【其他】

public boolean canJump(int[] nums) {

  int tmp = 0;
  for (int i=0; i<nums.length; ++i) {
    if (i > tmp) return false;
    tmp = Math.max(tmp, i + nums[i]);
  }
  return true;
}

 posted on 2018-10-27 10:36  alau  阅读(414)  评论(0编辑  收藏  举报