How about my implementation?


  • 3
    R

    `class Solution {
    public:
    bool canJump(int A[], int n) {

        int nearest=n-1;
    	for(int i=n-2;i>=0;--i)
    	{
    		if(i+A[i]>=nearest)
    			nearest=i;
    	}
    	return nearest==0;
    }
    

    };`


  • 0
    F

    Nice code, but you don't handle the case n = 0. Here is my code, every time we just need to check the reachable states. If the current state is not reachable, return false, and if the current state is beyond the last state, return true.
    Last statement 'n == 0' is for handling the case n = 0.

    bool canJump(int A[], int n) {
        for (int p = 0, i = 0; i < n && i <= p; i++) {
            p = max(i+A[i], p);
            if (p >= n-1) return true;
        }
        return n == 0;
    }

  • 0
    R

    I don't agree with you. It says that "you are initially positioned at the first index of the array", which means that the array has at least one element. so it's impossible that n equals to 0.


Log in to reply
 

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