动态规划系列(4) leetcode Java篇

第一题:

给定一个非负整数数组 nums ,你最初位于数组的 第一个下标 。

数组中的每个元素代表你在该位置可以跳跃的最大长度。

判断你是否能够到达最后一个下标。

class Solution {
    public boolean canJump(int[] num) {
        int len = num.length;
        if(len==1){
            return true;
        }
        int most = 0;
        for (int i = 0; i < len - 1; i++) {
            if (i <= most) {
                most = Math.max(i + num[i], most);
                if (most >= len - 1) {
                    return true;
                }
            } else {
                return false;
            }
        }
        return false;
    }
}

第二题:

给你一个非负整数数组 nums ,你最初位于数组的第一个位置。

数组中的每个元素代表你在该位置可以跳跃的最大长度。

你的目标是使用最少的跳跃次数到达数组的最后一个位置。

假设你总是可以到达数组的最后一个位置。

class Solution {
    public int jump(int[] num) {
        int len = num.length;
        if(len==1){
            return 0;
        }
        int most = 0;
        int end = 0;
        int cnt = 0;
        for (int i = 0; i < len - 1; i++) {
            most = Math.max(most, num[i] + i);
            if (i == end) {
                end = most;
                cnt++;
            }
        }
        return cnt;
    }
}
经验分享 程序员 微信小程序 职场和发展