LeetCode 55. Jump Game 跳跃游戏(Java)

题目:

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

开始自己的思路为:

  1. 判断数组中是否为0,如果没有0,则一定可以跳至数组最后一个索引处。(一个一个跳都可以到达)所以只需判断数组中是否有0的情况
  2. 从后向前遍历数组(从倒数第二个开始遍历即可),遍历到数组中为0元素处 i ,则需要判断 i 前面的位置是否能跳过当前0的位置
  3. 取 i 的前一位指针 j ,若 i 前某一位置元素满足 nums[j] > i-j,则说明可以跳过0的位置。否则若当 j==-1,则说明前面所有元素都无法跳过,return false
class Solution {
    public boolean canJump(int[] nums) {
        int i = nums.length-2;
        while(i >= 0) {
            if(nums[i]==0) {
                int j = i-1;
                while(j >= 0) {
                    if(nums[j] > i-j) {
                        break;
                    }
                    j--;
                }
                if(j == -1){
                    return false;
                }
            }
            i--;
        }
        return true;
    }
}
解法二:贪心算法

看他人解法,最多的采用的是贪心算法的思想。计算出当前能够跳出的最远处,若能跳出的最远处大于最后一个元素的位置,则说明能到达,return true;若到达当前点后,无法再往后跳,则不能达到终点,return false。

解题思路为:

  1. 定义变量temp,表示当前元素处能跳到的最远距离。其中,temp的取值为当前能跳出的最大距离和当前点+当前点能跳出的最大距离中的较大值,即temp = Math.max(nums[i]+i, temp);
  2. 当temp的值 >= 该数组的长度,就证明它里面肯定存在至少一种跳法,能够刚好跳到终点
  3. 当temp的值 < 遍历到的当前 i 的值时,就证明它跳不到终点
class Solution {
    public boolean canJump(int[] nums) {
        int temp = 0;
        for(int i=0; i<nums.length; i++) {
            temp = Math.max(nums[i]+i, temp);
            if(temp >= nums.length-1) {
                return true;
            } 
            if(temp <= i) {
                return false;
            }
        }
        return false;
    }
}
补充:贪心算法

贪心算法:即在每一个阶段,可以认为所作决定是好的,而不考虑将来的后果。
这里是详细的他人的讲解:算法(六):图解贪婪算法

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值