【LeetCode】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.

Example:

Input: [2,3,1,1,4]
Output: 2
Explanation: 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.

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/jump-game-ii
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

感觉这种题目叫做贪心?

CPP

class Solution {
public:
    int jump(vector<int>& nums) {
        int step=0,maxsize=0,end=0;
        for(int i=0;i<nums.size()-1;i++){
            maxsize=max(maxsize,nums[i]+i);
            if(i==end){
                end=maxsize;
                step++;
            }
        }return step;
    }
};

大佬的答案,优化了点?

class Solution {
public:
    int jump(vector<int>& nums) {
        if(nums.size()<=1) return 0;
        int end = nums[0];
        int maxpos = nums[0];
        int cnt= 0;
        for(int i = 0; i < nums.size();++i)
        {
            if(i>end)
            {
                cnt++;
                end = maxpos;
                
            }
            maxpos = max(maxpos,i+nums[i]);
        }
        return ++cnt;
    }
};

java

 

class Solution {
   public int jump(int[] nums) {
    int end = 0;
    int maxPosition = 0; 
    int steps = 0;
    for(int i = 0; i < nums.length - 1; i++){//找能跳的最远的
        maxPosition = Math.max(maxPosition, nums[i] + i); 
        if( i == end){ //遇到边界,就更新边界,并且步数加一
            end = maxPosition;
            steps++;
        }
    }
    return steps;
   }
}