Greedy

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.)

求到达最后元素的最少步数。用贪心法求解,从nums[0]开始遍历,设从当前位置i所能到达的最远距离为coverPos,那么从i+1到coverPos进行遍历,寻找从该范围内的位置出发所能到达的最远距离,记录能到达最远距离的出发点j为当前所走一步的终点。再次遍历时,从j开始,遍历j+1到新的coverPos之间的位置,以此类推直到coverPos能覆盖最后一个元素为止。

class Solution {
public:
    int jump(vector<int>& nums) {
        int n=nums.size();
        if(n<=1) return 0;
        int steps=0;
        int coverPos=0;
        for(int i=0;i<n;){
            if(nums[i]==0) return -1;
            coverPos=nums[i]+i;
            steps++;
            if(coverPos>=n-1){
                return steps;
            }
            int maxDistance=0;
            for(int j=i+1;j<=coverPos;j++){
                if(nums[j]+j>maxDistance){
                    maxDistance=nums[j]+j;
                    i=j;
                }
            }
        }
        return steps;
    }
};

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.

For example:
A = [2,3,1,1,4], return true.

A = [3,2,1,0,4], return false.

与上一题基本相同,只要判断能否到达最后的元素。依然是贪心的思路,每次把当前位置出发所能到达的最远位置存储在cover中,每次循环时判断当前位置是否在cover的范围内,一旦当前位置超出cover,则返回false。当cover达到最后元素时返回true。

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



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值