[leetcode] 45.Jump Game II

问题描述:
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.

Your goal is to reach the last index in the minimum number of jumps.

For example:
Given array A = [2,3,1,1,4]

The minimum number of jumps to reach the last index is 2. (Jump 1 step from index 0 to 1, then 3 steps to the last index.)
题目的意思:与第55题不同的地方是,这次需要让你找出从起始位置跳最少得步骤能够到达最后一个元素的位置。

题目的意思清楚了,这次依旧是使用贪心的算法。我们以下图为例:数组A的元素是3,4,3,1,0,7.对于每个位置i,最少能往前跳一步,最多能往前跳A[i]步长。我们定义i可达区间即f(i) = [i+1,i+A[i]],图中A[0]元素的可达区间就是[1,3]。局部的最优解定义是i往后跳了j步到达可达区间f(i), 该可达区间内元素能够跳到的最远距离对应的可达区间内元素下标就是局部最优解。比如对于在起始位置0,可达区间是[1,3],[1,3]内元素能够跳到最远的距离是位置5,所以下一跳地址应该是位置1或者2(1跟2都是到达最远位置5,我的代码里是选择2)
一个例子

class Solution {
public:
    int jump(vector<int>& nums) {
        if(nums.size() == 0 || nums.size() == 1)return 0;
        int index = 0;
        int count_step = 0;
        while(index < nums.size()){
            count_step++;
            int next_index = index;
            int max_step = 0;
            for(int i = nums[index]; i >= 1; --i){
                if(i + index > nums.size() - 1)continue;
                else if(index + i == nums.size() - 1)return count_step;
                else if(index + i + nums[index + i] == nums.size() - 1)return count_step + 1;
                if(max_step < i + nums[index + i]){
                    next_index = index + i;
                    max_step = i + nums[index + i];
                }
            }
            index = next_index;
        }
        return -1;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值