A simple C++ answer


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

    The key to the problem is that you should jump as far as you can with the use of greedy strategy.


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

    good answer and you can make it in this way


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.