C++ solution: only check '0's


  • 0
    J

    We iterate from the end of array, once we detect a 0, we then go and check whether there are previous elements in the array that can jump over this 0 or not. If no such element exist, return false.

        bool canJump(vector<int>& nums) {
            if (nums.size() <= 1) return true;
            int i = nums.size()-2;
            while (i >= 0) {
                if (nums[i] > 0) i--;
                else {
                    int delta = 1;
                    while (i-delta >= 0) {
                        if (nums[i-delta] <= delta)
                            delta++;
                        else break;
                    }
                    if (i-delta < 0) return false;
                    else i = i-delta;
                }
            }
            return true;
        }
    

Log in to reply
 

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