[LeetCode55]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:
Note that the A[i] means the maximum jump length. In other words, it is possible that we move j step (Use one variable to store current maximum jump index
Java
public boolean canJump(int[] A) {
        int jmax = 0;
        for(int i = 0;i<A.length;i++){
        	if(i<=jmax){
        		jmax = Math.max(jmax, A[i]+i);
        	}else {
				return false;
			}
        }
        return true; 
    }

c++
bool canJump(int A[], int n) {
      int maxCover = 0;
    for(int start = 0; start<=maxCover &&start<n;start++){
        if(A[start]+start > maxCover)
            maxCover = A[start]+start;
        if(maxCover >=n-1)
            return true;
    }
    return false;
    }

좋은 웹페이지 즐겨찾기