Jump Game leetcode java

愛做飯的小瑩子發表於2014-07-28

題目

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.

 

題解

 參考了http://fisherlei.blogspot.com/2012/12/leetcode-jump-game.html的程式碼

 很巧妙的解法,程式碼很短,看著一眼就能看懂,但自己想不見得想的出來,好好品味一下

程式碼如下:

 

 1     public boolean canJump(int[] A) {  
 2             int maxCover = 0;  
 3             for(int start =0; start<= maxCover && start<A.length; start++)  
 4             {  
 5                  if(A[start]+start > maxCover)  
 6                       maxCover = A[start]+start;  
 7                  if(maxCover >= A.length-1) 
 8                     return true;  
 9             }  
10             return false;  
11        } 

相關文章