Leetcode jump Game II

OpenSoucre發表於2014-07-04

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

題目是假設輸入陣列能滿足到達陣列末尾的條件,求出最少的跳數。

題目給出的測試用例是[2,3,1,1,4]

第一次從開頭跳,則跳得位置為0+A[0]=2,故在位置2

根據貪心策略下次跳的時候應該選擇1~2之間跳的最遠的位置開始跳

1的位置跳的距離為1+A[1]=4

2的位置跳的距離為2+A[2]=3

故下一步選擇從1的位置開始跳剛好能跳到最後結束

class Solution {
public:
    int jump(int A[], int n) {
        int res = 0, last = 0, cur = 0;
        for(int i = 0 ; i < n; ++ i){
            if(i > last) last = cur,res++;
            cur = max(cur,A[i]+i);
        }
        return res;
    }
};

 

相關文章