算法设计与分析课作业【week13】leetcode--55. 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.

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的数上是2,则说明我们在0这个下标下可以移动到下标为1和2,在1的下标下则可以移动到下边为2,3,4的位置,让我们判断能否从数组的第一个位置移动到最后一个位置。我们可以使用贪心算法,计算出每一个下标能够移动到的最远的位置,最后判断是否有一个最远的位置能够到达数组的最后一位即可。

我们可以使用贪心算法,计算出每一个下标能够移动到的最远的位置,最后判断是否有一个最远的位置能够到达数组的最后一位即可。我们首先要知道,当我们得到一个最远的位置时,在这个最远的位置前的下边说明都是可以移动到的,而超出最远位置的下标则是到不了的。所以我们在遍历数组时,还要注意目前的下边有没有超过最远位置,如果超过便可以停止了。

C++代码如下:

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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值