Jump Game

LeetCode #55


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.

Determine if you are able to reach the last index.

Example:

For example:
A = [2,3,1,1,4], return true.

A = [3,2,1,0,4], return false.

Idea:

简单,每一步update最远能跳到的地方,如果超过或者达到end,就return true。

max_jump = max(max_jump, i+nums[i]);

Code:

class Solution {
public:
    bool canJump(vector<int>& nums) {
        int max_jump=0;
        int last=nums.size()-1;

        for(int i=0; i<nums.size(); ++i){
            max_jump = max(max_jump, i+nums[i]);

            if(max_jump>=last) return true;

            if(max_jump == i) return false;
        }

    }
};

results matching ""

    No results matching ""