[leetcode]55. Jump Game ,C++/PYTHON实现,medium难度

17 篇文章 0 订阅
3 篇文章 0 订阅

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.
Subscribe to see which companies asked this question

这个题的意思是跳棋游戏,就是给你一组正整数,每一个代表能往后跳多少个位置。
如果从第一个跳到最后那个数,就返回成功否则返回失败。
比如说[1,0],从第一个能往后跳1个,到了最后一个不管最后一个是多少,反正就是True
再说[0 ,1],从第一个只能往后跳0个,也就是跳不到,返回false

怎么做呢,用贪心算法。

意思是说:不管每一步怎么跳,我都跳到最后,跳到不能跳为止。
比如我们用一个变量G,来记录我能跳到的最后的位置。对第i步来说,从第i个位置出发的最远是 nums[i]+i 那么我们的 G=max(G,nums[i]+i)
如果在某一步i>G,也就是说,前面能跳到的最远距离跳不到i,那就肯定失败。
如果最终能跳到最后一步就返回成功。
代码如下:

C++

class Solution {
public:
    bool canJump(vector<int>& nums) {
        int len = nums.size();
        if (!len)return false;
        int G = nums[0];
        for(int i =1; i!=len;i++){
            if(G<i)return false;
            G = max(G,nums[i]+i);
            if(G>=len-1)return true;
        }
        return G>=len-1;
    }
};

python


class Solution(object):
    def canJump(self, nums):
        """
        :type nums: List[int]
        :rtype: bool
        """
        L = len(nums)
        if L==0:
            return False
        G = nums[0]
        for i in range(1,L):
            if G<i:
                return False
            G=max(G, nums[i]+i)
            if G>=L-1:
                return True
        return G>=L-1
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值