• 55.Jump Game


    给定一个数组,数组中的数字,代表当前元素的最大跳转值,可以不用跳转到最大的跳转值,比如下标 0 的值为3,可以跳转到下标 1,2,3均可,求,是否能跳转到最后一个下标。

    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.

    思路:
    利用一个变量,保存为当前可到达的最大下标值 res,每一次移动,都将之前保存的最大值 res,与当前下标 [i+nums[i]] 比较,保存其中最大的一个。看最后是否能到达终点。
    难点:当最大值res = i 时,表示不能往下走了。

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

    Java 版:

      • 动态规划,用一个数字 idx,记录能到达的最远下标,每一次遍历后,更新能到达的最远下标;
      • 当更新后,发现,能到达的最远下标就是当前所处的下标位置,也就是说:跳不动了,返回 false;
      • 当最远下标能达到最后一个位置时,直接返回 true。

    class Solution {
        public boolean canJump(int[] nums) {
            if(nums.length <= 1) return true;
            int idx = 0; //最远能到达的位置下标
            for(int i = 0; i < nums.length; i++){
                if(i + nums[i] > idx) idx = i + nums[i]; //更新最远能到达的位置
                if(i == idx) return false; //更新后,最远能跳到的位置,就是当前所处的位置,跳不动了
                if(idx >= nums.length - 1) return true; //如果已经能到达最后一个位置了,返回 true
            }
            return false;
        }
    }
  • 相关阅读:
    分布式事务
    事务
    shell 脚本编写
    使用fail2ban 防止ssh暴力破解
    数据加密
    英文字符串排序算法
    SpringCloud-ServerConfig 配置中心服务端 / 客户端
    maven setting参考配置
    java面向对象设计原则
    Java Object
  • 原文地址:https://www.cnblogs.com/luo-c/p/12987493.html
Copyright © 2020-2023  润新知