[leet code] Jump Game

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.

============

Analysis:

It is an interesting problem, nothing about data structure or classical algorithm, but more about the logical ability of the applicant (I guess).

The first difficulty is to throughly understand the problem.  Values of each array element indicates the "maximum" jump length.  Which means if the value is 3, then it can jump 1 step, 2 steps or 3 steps.  In another world, the only factor that would impact the result is the value of 0.  (if there is no 0 element, end index must be able to reach, like by jumping 1 step each time).

Therefore, we only need to focus on the value 0 elements. In order to jump through the 0 element, at least one element that is prior to the examining 0 element need to have the "ability" to jump further than the distance between this element and the examining 0 element.  For example, in array [2,3,1,0,4], the 3rd element (1) cannot jump through the 0 element, but the 2nd element (3) can jump through the 0 element.  Accordingly, if no prior element can jump through the 0 element, program can return false.

public class Solution {
    public boolean canJump(int[] A) {
        if(A.length == 1) return true;
        
        int count = 0;
        for(int i=A.length-2; i>=0; i--){// check all the 0 elements existing in the array
            if(A[i] == 0) {
                // flag indicates if there is any prior element can jump through this 0 element
                boolean jumpFlag = false;
                for (int j=i-1; j>=0; j--){
                    if(A[j]>i-j) { // jth element is able to jump through this 0 element
                        jumpFlag = true; 
                        break;
                    }
                }
                if(jumpFlag == false) return false; // no prior elements can jump through this 0 element
            }
        }
        return true;
    }
}

 



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章