【leetcode】jump-game-ii

Title description

Given an array of non-negative integers, you are initially at the position of the first element of the array. The elements in the array represent the maximum length you can jump at this position. Your goal is to use the least number of jumps to reach the last element of the array s position. For example, given the array A =[2,3,1,1,4], it takes at least two times to jump to the position of the last element of the array. (From the position where the array index is 0, jump length 1 to the position of index 1, and then jump length 3 to the position of the last element of the array)

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 is2. (Jump1step from index 0 to 1, then 3 steps to the last index.)

problem analysis

       Take a jump from a certain position i, and jump to position A[i]+i as far as possible, then to any position in position i+1~i+A[i] only one step is required, and only one position is required to meet the jump You can jump to the farthest distance after taking off at this position. The problem can be divided into sub-problems, by obtaining the optimal solution of the sub-problems, solving the longest distance, and obtaining the overall optimal solution.

Analysis of Algorithms

This problem can be solved through greedy thinking. By solving the local optimal solution, that is, the longest distance of the local jump, the minimum number of jumps is obtained. For position i, you can jump to i+A[i], and define i+A[i] as cur. Then in the range of i+1 to cur, find the maximum value of the jump that can be jumped in this range. Record the farthest distance to jump through the last variable and compare it with the current position. If it is less than the current position, set it to the farthest distance cur that can be jumped at present, and increase the number of jumps by 1. The time complexity of the algorithm is O(n).

Coding implementation

public class Solution {
    public int jump(int[] A) {
        int cur=0;  
        int last=0;  
        int step=0; 
        for(int i=0; i<A.length && cur>=i; i++)
        {
            if(i>last)
            {
                last=cur;
                step++;
            }
            cur =cur>(A[i]+i)?cur:(A[i]+i);
        }
        return step;
	}
}

 

Guess you like

Origin blog.csdn.net/VinWqx/article/details/104909577