LeetCode 55. Jump Game

来源:互联网 发布:死亡代理人知乎 编辑:程序博客网 时间:2024/05/15 04:33

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.

A = [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