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.

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

Lintcode_ladder

Method

  1. x
  2. x

Example

  1. 1
class Solution {
public:
    /**
     * @param A: A list of lists of integers
     * @return: An integer
     */
    int jump(vector<int> nums) {
        // wirte your code here
        if (nums.empty()) {
            return 0;
        }
        int n = nums.size();
        // int curstep = nums[0];
        int curmax = 0;
        int curend = 0;
        int count = 0;
        for (int i =0; i < n-1; ++i) {
            // get the current max jump, before real jumping
            curmax = max(curmax, i + nums[i]);
            // when reach the max current jump,
            // record this jump,
            // and update the max possible jumping we can
            if (i == curend) {
                count++;
                curend = curmax;
            }
        }
        return count;
    }
};

Similar problems

x

Tags

x

results matching ""

    No results matching ""