【LeetCode】55. Jump Game

来源:互联网 发布:php nodejs 共存 编辑:程序博客网 时间:2024/06/08 13:58

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.

  • Difficulty: Medium
贪心算法,思路是每一步确定能走的最大步数,如果中途出现最大步数为0的情况,则不能走到终点,如果中途出现最大步数大于当时的下标距离终点的距离,则可以到达

时间复杂度O(n)

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


0 0