LeetCode 55. Jump Game

阅读 37

2023-09-05


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.

For example:

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

class Solution {
public:
    bool canJump(vector<int>& nums) {
        int start = 0,end = 0;
        while(end < nums.size()){
            int max = 0;
            for(end = start;end < nums.size(); end ++){
                if(nums[end] == 0) break;
            }
            if(end >= nums.size() -1) return true;
            for(int i = start; i < end; i ++){
                int temp = nums[i] - (end - i);
                if(temp > max) max = temp;
            }
            if(max <= 0){
                return false;
            }
            nums[end] = max;
            start = end;
        }
        return true;
    }
};





精彩评论(0)

0 0 举报