C++ Solution, Consider only the ZERO values


  • 0
    J

    The idea is to deal with only the zero values, very efficient if there are only several locations that has zero value in a large array. If all the zeros can be skipped by jump at previous locations, it return true. If any zero value is not able to be skipped, return false immediately.

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

Log in to reply
 

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