zoukankan      html  css  js  c++  java
  • LeetCode_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.)
    

      Greedy:  keep the current maximum reach distance, and the number of steps to reach this current maximum distances, and keep another variable to record the next maximum reachable distance, which cost the current steps plus 1. The key idea behind is that, all the positions before the maximum reachable distance would be able to be reached! Then we linear scan the array to keep updating the current maximum and the next maximum as well as the number of steps. We can achieve the linear time algorithm

    class Solution {
    public:
        int jump(int A[], int n) {
            // Start typing your C/C++ solution below
            // DO NOT write int main() function
            int steps = 0;
            int currMax = 0;
            int nextMax = 0;
            for(int i = 0; i< n; i++)
            { 
              if(i > currMax)
              {
                currMax = nextMax;
                steps++;
              }
              
              nextMax = nextMax > i+A[i] ? nextMax : i+A[i] ; 
            
            }
                return steps ;
        }
    };
  • 相关阅读:
    bzoj3530 [SDOI2014]数数
    bzoj3940 Censoring
    线性代数基础
    hdu1085 Holding Bin-Laden Captive!
    hdu1028 Ignatius and the Princess III
    luogu2000 拯救世界
    博弈论入门
    树hash
    luogu2173 [ZJOI2012]网络
    luogu1501 [国家集训队]Tree II
  • 原文地址:https://www.cnblogs.com/graph/p/3210226.html
Copyright © 2011-2022 走看看