55. Jump Game

来源:互联网 发布:画网络拓扑图的软件 编辑:程序博客网 时间:2024/04/30 07: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.

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

解题思路:
该题的意思是nums[i]是能跳的最大数值,两个元素间隔为1.故可以用贪心,每次都求能跳的最大看是否能跳到n-1。
class Solution{
public:
          bool Canjump(vector<int> &nums){
                     if(nums.empty()) return false;
                     int maxstep=nums[0];
                     int len=nums.size();
                     for(int i=1;i<len;i++)
                     {
                          
                            if(maxStep==0)
                                 return false;
                           else if(maxStep<0)
                                 return false;
                           else{
                                 maxStep=max(--maxStep,nums[i]);
                        }

                     }
                   return true;
                    
         }
}
原创粉丝点击