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;    
}

 

 

posted @ 2017-12-05 10:36  hozhangel  阅读(144)  评论(0编辑  收藏  举报