Leetcode: 跳跃游戏(Jump Game)(C++)

17 篇文章 0 订阅
17 篇文章 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.

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的情况,而之前的值又不如0大,可以直接结束循环,我这里用的i > 0 ? range[i-1] >= i : true来判断。其实还能更简化的,在for循环中加入判断,如果结果大于nums_size - 1就可以直接输出true

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

时间20ms


最快(0ms)

class Solution {
public:
    bool canJump(vector<int>& nums) {
        ios::sync_with_stdio(false);
        cin.tie(nullptr);
        cout.tie(nullptr);
        int n = nums.size();
        int maxRight = 0;
        for (int i = 0; i < n; ++i){
            if (i > maxRight) return false;
            maxRight = ((i+nums[i])>maxRight)?(i+nums[i]):maxRight;            
        }
        return true;
    }
};

前面三行是优化输入输出部分的大概能把我代码优化4ms

它这里用maxRight记录最大的值,在遍历nums的同时更新该数据。若maxRight<i 则跳跃不到i处返回false,否则遍历到结束时返回true

但是除了空间以外并没有在时间上有什么优化,所以这个0ms到底怎么来的,甚至我运行他的代码显示16ms和我代码加上它前三行后效果一样

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值