Likou Brushing Notes: 45. Jumping Game II

Question : 45. Jump Game II is
given an array of non-negative integers, and you are initially at the first position of the array.

Each element in the array represents the maximum length you can jump at that position.

Your goal is to use the least number of jumps to reach the last position of the array.

Example:

Input: [2,3,1,1,4]
Output: 2
Explanation: The minimum number of jumps to the last position is 2.
Jump from subscript 0 to the position of subscript 1, skip 1 step, and then skip 3 steps to reach the last position of the array.
Description:

Suppose you can always reach the last position of the array.

Ideas

  • Main idea: Greedy
  • Forward traversal, find the farthest distance you can jump to, max_t saves the number of steps, end saves the position of the previous step, when i reaches end, assign max_t to end

Source code

class Solution {
    
    
public:
    int jump(vector<int>& nums) {
    
    
        int n = nums.size();
        int count = 0;
        int max_t = 0;//最大步数
        int end =0;//当时的结尾
        for(int i = 0; i < n - 1; ++i){
    
    
           if(max_t >= i){
    
    
               max_t = max(max_t, i + nums[i]);
               if(i == end){
    
    
                   count++;
                   end = max_t;
               }
           }
        }
        return count;
    }
};

Guess you like

Origin blog.csdn.net/qq_45914759/article/details/109340830