数据结构与算法[LeetCode]——Jump Game I II

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.

/*题意:从0开始向后跳,每次跳的最大步数为A[i],看能否跳到数组结尾n-1处。
 *从前向后扫描,依次遍历当前能跳到的步数,找出最大能到哪位。如果max满足max>=n-1(下标),则说明可以跳到最后。
 * */
class Solution{
public:
    bool canJump(int A[],int n){
    int i=0;
    int J_max=A[0];
    for(int i=1;i<=n-1 && i<=J_max;++i)
    { 
      J_max=max(J_max,i+A[i]);
    }
    return J_max >= n-1;
    }
};


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

/*
 *贪心算法

 *求最小跳数,类似于“安排活动”问题,找到每一轮最大的范围,这样局部区间最大,轮数就会少。
 *接下来问题就是求每一轮后局部最大区间
 * */

class Solution{
public:
     int jump(int A[],int n){
     if(n==1)return 0;
     
     //从i==1(n>=2)开始  
     int right=1;
     int left=A[0];
     int step=1;
     int left_max=left;
     int i=0;

     while(left_max<n-1)
     {
        step++;
        int flag=0;
        for(i=right;i<=left;++i){
           if(i+A[i]>left_max){
               left_max=i+A[i];
               right=i+1;
               flag=1;  //left_max 向左有挪动,标志位置位。
           }
        }
        left=left_max;  //每一轮调整一次left边界

        if(flag==0){  //说明该轮过后,一直没能继续向前跳(left_max 没有变化了),说明永远不能达到last index
           step=0;
           break;   
           }
        }
     return step;
     }
};




 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值