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.

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

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

题目是看能不能根据每一跳的最大步长跳到最后的位置。开始用了DP,建一个布尔数组,遍历步长数组,把能到达的位置都置为true,最后判断最后一位是true还是false。

贴一下代码吧:

    public boolean canJump(int[] nums) {
        int len = nums.length;
        boolean can[] = new boolean[len];

        can[0] = true;
        for(int i = 0;i < len;i++){
            if(can[i] == true){
                for(int j = 0;j <= nums[i] && (i + j < len);j++){
                    can[j + i] = true;
                }
            }
        }

        return can[len - 1];
    }

然后就,华丽丽的TLE了。后来转念一想,应该用贪心,每次都往最远的地方走。

这时可以设置一个变量maxStep记录当前能够走的最远步数,往前移动一位就减一,同时与该位的步数进行比较,如果小的话,说明在这一位置能够走更远, 对maxStep进行更新。结束条件就是当前位置的坐标与maxStep之和能够大于数组长度。

上代码:

public boolean canJump(int[] nums){
        int len = nums.length;
        if(len == 0 || len == 1)    return true;
        int maxStep = nums[0];

        for(int i = 1;i < len;i++){
            if(maxStep == 0)    return false;
            maxStep--;
            if(maxStep < nums[i])   maxStep = nums[i];
            if(maxStep + i >= len - 1)  return true;
        }
        return false;
    }

71 / 71 test cases passed.
Status: Accepted
Runtime: 364 ms


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.

Your goal is to reach the last index in the minimum number of jumps.

For example:
Given array A = [2,3,1,1,4]

The minimum number of jumps to reach the last index is 2. (Jump 1 step from index 0 to 1, then 3 steps to the last index.)

II是还要求出最小跳数,也就是要记录每一步是在哪儿跳的。还是用贪心。设置两个游标,一个记录当前能够到的最远位置curr,一个记录跳的停留的位置last。

大概的思路是:curr只顾着往前找能调到的最远位置就行,last负责记录每一步在那儿跳的,当i大于last时,就说明要跳了,这时候跳数增加,last更新到curr的位置。

另外,当i>curr时,说明已经超越了当前最远的位置,也就是到不了终点了。

public int jump(int[] nums){
        int last = 0;
        int curr = 0;
        int times = 0;

        for(int i = 0;i < nums.length;i++){
            if(i > curr)    return -1;
            if(i > last){
                last = curr;
                times++;
            }
            curr = Math.max(curr, i + nums[i]);
        }
        return times;
    }

91 / 91 test cases passed.
Status: Accepted
Runtime: 400 ms

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值