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;    
    }
  • 相关阅读:
    maven完成构建后,eclipse导入运行maven web
    maven构建java项目的过程【完全】
    maven配置【转载】
    iOS - 移动设备防丢失App
    iOS
    iOS
    iOS
    iOS
    iOS
    iOS
  • 原文地址:https://www.cnblogs.com/hozhangel/p/7900322.html
Copyright © 2011-2022 走看看