LeetCode !! 55. jump game

参考资料:leetCode 评论区大佬 + 左程云算法课

55. Jump Game
You are given an integer array nums. You are initially positioned at the array's first index, and each element in the array represents your maximum jump length at that position.

Return true if you can reach the last index, or false otherwise.

 

Example 1:

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

思路:用一个变量max 记录准备到达位置i时,能够到达的最远位置.
检查 能不能真正地抵达 位置 i , 即判断max<i ? ,if true, then that means we cannot reach i . So just return false.
如果我们遍历完整个数组都还没有返回false,说明 我们能够抵达终点,所以返回 true.

public boolean canJump2(int[] nums) {
        if(nums==null || nums.length<2)
        {
            return true;
        }

        int n = nums.length;
        int max = nums[0];
        for(int i=1;i<n;i++)
        { // max means the bound that we can reach before we get i, and now i is 1,2,3...
         // max 表示预备到位置i时,我们所能够到的最远位置
            if(i>max){return false;};
            max = Math.max(max,i+nums[i]);
        }
        return true;
    }
ylem
ylem
未知归属地
2020-03-30
C++

其实很简单!

想象你是那个在格子上行走的小人,格子里面的数字代表“能量”,你需要“能量”才能继续行走。

每次走到一个格子的时候,你检查现在格子里面的“能量”和你自己拥有的“能量”哪个更大,取更大的“能量”! 如果你有更多的能量,你就可以走的更远啦!~

class Solution {
public:
    bool canJump(vector<int>& nums)
    {
        if(nums.size() == 0)
            return true;

        int cur = nums[0], i = 1;
        for(; cur != 0 && i < nums.size(); i++)
        {
            cur--;
            if(cur < nums[i])
                cur = nums[i];
        }
        return i == nums.size();
    }
};

下面是Java版本,把cur视作准备到第i位置时的血量,登录到这个位置i需要花费一个血。
如果当前位置的血瓶比自己血多,就重置自己的血量。
如果没血量或遍历到尽头了,那么就跳出循环。

  public boolean canJump(int[] nums) {
        int n = nums.length;
        int cur = nums[0];
        int i=1;
        for(;cur!=0&&i<n;i++)
        {
            cur--;
            if(cur<nums[i])
            {
                cur = nums[i];
            }
        }
        return i==n;// false means 血量耗尽了,才到这一步
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值