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

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

class Solution {
public:
    int jump(vector<int>& nums) {
        int step=0,left=0,right=0;//left means last chosen position. right means current farthest reached position.
        for(int i=0;i<nums.size()-1;i++){
            right=max(right,i+nums[i]);//update the farthest position
            if(i==left)step++,left=right;// step+1, update the left position
        }
        return step;
    }
};

 

posted @ 2017-04-04 16:12  Tsunami_lj  阅读(79)  评论(0编辑  收藏  举报