1. 程式人生 > >leetcode 45. Jump Game II

leetcode 45. Jump Game II

nbsp 什麽 sent leetcode minimum span ini rst blog

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

Note:
You can assume that you can always reach the last index.

題意:

就當有N塊石頭吧,在第i塊石頭上最遠可以跳nums[i]塊石頭,問最少跳多少次可以從第一塊石頭跳到最後一塊。

思路:

目測數據範圍很大,要用O(N)的方法。

設far為從0-i的石頭上最遠可以跳到哪裏。

prePos 為在跳ans步的時候,最遠可以跳到什麽地方。

則當i>prePos時,跳ans步已經跳不到i點了,我們需要++ans,並修改prePos為0~i-1最遠可以跳到的地方,我們知道far為之前的點最遠可以跳到的位置,這個跳包括跳躍次數為ans+1的和<=ans的,因此跳ans+1步最遠可以跳到的位置就是prePos。

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

leetcode 45. Jump Game II