Leetcode:45. Jump Game II

Description

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.

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

Example

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

思路

  • 算是一个贪心吧。每次选择下一次能够达到的最远的那个点去跳跃

代码

class Solution {
public:
    int jump(vector<int>& nums) {
        int len = nums.size();
        if(len == 1) return 0;
        
        int i = 0, j = 0, count = 0, maxflag = -1, index = -1;
        while(i < len){
            if(nums[i] > 0) count++;
            for(j = i + 1; j <= i + nums[i]; ++j){
                if( j + nums[j] >= maxflag){
                    index = j;
                    maxflag = j + nums[j];
                }
                
                if(j == len - 1) return count;
            }
           
            i = index;
        }
        
        return count;
    }
};
posted @ 2017-05-12 22:05  JeffLai  阅读(73)  评论(0编辑  收藏  举报