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

    Note:
    You can assume that you can always reach the last index.

     https://leetcode.com/problems/jump-game-ii/discuss/

    int jump(int* nums, int numsSize) {
         if(numsSize < 2)return 0;
         int level = 0, currentMax = 0, i = 0, nextMax = 0;
    
         while(currentMax - i + 1 > 0){        //当前level的元素个数大于0
             level++;
             for(; i <= currentMax; i++){    //遍历当前level,更新能达到的最大下标
                if(nextMax < nums[i]+i) nextMax = nums[i]+i;
                if(nextMax >= numsSize-1) return level;   // 如果能达到的最大下标包括当前数组的最大下标,就返回当前的level 
             }
             currentMax = nextMax;  //currentMax代表当前level的元素能跳到的最大下标,也就是下一个level的最大下标
         }
         return 0;    
    }
  • 相关阅读:
    数与bit
    ARM汇编优化1
    一 *(a+1)与*(&a+1)
    二 *(a+1)多维数组
    三 二维数组取址
    四 sizeof(a)
    永恒之蓝及WannaCry分析
    github使用记录
    三种页面置换算法的C++模拟
    opencv检测图像直线
  • 原文地址:https://www.cnblogs.com/hozhangel/p/7900322.html
Copyright © 2011-2022 走看看