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

    尝试着用英文来写题解,用英文给代码加注释!有很多事情看上去很难,如果一直退缩着,

    就永远还是只会惊呼那些做到的人那么的牛逼, 倒不如现在就狠下心来逼上自己一把!

    附上代码:

     1 class Solution {
     2 public:
     3     int jump(int A[], int n) {
     4         // last: keep the track of the maximum distance
     5         // that has been reached by using "cnt" steps
     6         // whereas next is the maximum distance that
     7         // can be reached by using "cnt+1" steps
     8         // thus next = MAX(A[i]+i) where 0 <= i <= last
     9         int last = 0, cnt = 0, next = 0;
    10         for (int i = 0; i < n; i++) {
    11             if (i > last) {
    12                 // if "last" is not n-1 and 
    13                 // can't go further(which means last >= next)
    14                 // return -1 represents never reach the end
    15                 if (last >= next && last < n-1) {
    16                     return -1;
    17                 }
    18                 cnt++;
    19                 last = next;
    20             }
    21             next = max(next, A[i]+i);
    22         }
    23         return cnt;
    24     }
    25 };
  • 相关阅读:
    统计学方法(t-检验)
    generate的使用verilog
    FPGA的存储方式大全
    matlab函数
    三年后的我-记于2018
    labview学习——用户界面模式
    labview线程相关
    labview状态机
    JS~字符串长度判断,超出进行自动截取(支持中文)
    AngulaJs -- 隔离作用域
  • 原文地址:https://www.cnblogs.com/Stomach-ache/p/3741075.html
Copyright © 2011-2022 走看看