zoukankan      html  css  js  c++  java
  • 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.)

    思路:

    本能的想法仍然是动规,但是还是会超时。考虑在Jump Game的基础上进行更改,reach记录当前可到的最远距离,nextreach表示如果再走一步可到的最远距离,然后进行一次遍历,当reach不能满足要求时step加一,更新reach为nextreach。

    代码:

     1     int max(int a, int b){
     2         if(a > b)
     3             return a;
     4         return b;
     5     }
     6     int jump(int A[], int n) {
     7         // IMPORTANT: Please reset any member data you declared, as
     8         // the same Solution instance will be reused for each test case.
     9         if(n <= 1)
    10             return 0;
    11         int reach=A[0], nextreach=A[0];
    12         int i;
    13         int step=1;
    14         for(i = 1; i < n; i++){
    15             if(i > reach){
    16                 reach = nextreach;
    17                 step++;
    18             }
    19             nextreach = max(nextreach, i+A[i]);
    20         }
    21         return step;
    22     }
  • 相关阅读:
    安全扫描英汉对照意思
    文件包含漏洞
    文件上传漏洞
    XSS攻击
    常用命令
    适用于 Python 的 AWS 开发工具包 (Boto3)
    SQS 设置长轮询
    Amazon SNS 消息属性
    SQS Queues and SNS Notifications – Now Best Friends
    Policy Evaluation Logic 策略评估逻辑
  • 原文地址:https://www.cnblogs.com/waruzhi/p/3406069.html
Copyright © 2011-2022 走看看