45. Jump Game II

来源:互联网 发布:植物学 网络 编辑:程序博客网 时间:2024/05/24 06:56

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.

Solution 1 Greedy

public static int jump(int[] nums) {int maxReach = nums[0];int minStep = 1;int edge = nums[0];for (int i = 1; i < nums.length; i++) {if (i > edge) {edge = maxReach;minStep += 1;}maxReach = Math.max(nums[i] + i, maxReach);}return nums.length == 1 ? 0 : minStep;}

Solution 2 BFS

public static int jump2(int[] nums){if(nums.length < 2){return 0;}int level = 0;int currentMax = 0;int i = 0;int nextMax = 0;while(i <= currentMax){ level++;         for(;i<=currentMax;i++){   //traverse current level , and update the max reach of next level            nextMax=Math.max(nextMax,nums[i]+i);            if(nextMax>=nums.length-1){            return level;   // if last element is in level+1,  then the min jump=level             }         }         currentMax=nextMax;}return 0;}



0 0