【leetcode】jump-game-ii

題目描述

給出一個非負整數數組,你最初在數組第一個元素的位置,數組中的元素代表你在這個位置可以跳躍的最大長度,你的目標是用最少的跳躍次數來到達數組的最後一個元素的位置。例如,給出數組 A =[2,3,1,1,4],最少需要兩次才能跳躍到數組最後一個元素的位置。(從數組下標爲0的位置跳長度1到達下標1的位置,然後跳長度3到數組最後一個元素的位置)

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.)

問題分析

       從某一個位置i起跳,最遠可以跳到位置A[i]+i,那麼到位置i+1~i+A[i]中的任意位置只需要跳一步,只需要求解一個位置,滿足跳到該位置後起跳可以跳到最遠距離。該問題可以劃分爲一個個子問題,通過獲取子問題的最優解,求解最遠距離,獲取整體最優解。

算法分析

該問題可以通過貪心思想得到整體最優解。通過求解局部最優解即求解局部跳最遠距離,獲得最少跳躍次數。對於位置i,可以跳躍到i+A[i],定義i+A[i]爲cur。那麼在i+1到cur範圍內,求解該範圍內起跳所能跳的最大值。通過last變量記錄跳到最遠距離,與當前位置進行比較,如果小於當前位置,那麼置爲當前所能跳的最遠距離cur,跳躍次數加1。算法的時間複雜度爲O(n)。

編碼實現

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;
	}
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章