Last active
March 14, 2016 19:09
-
-
Save cangoal/ce3a55de8bb1c3c40441 to your computer and use it in GitHub Desktop.
LeetCode - Jump Game II
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public int jump(int[] A) { | |
// write your code here | |
int reach = 0, step = 0, max = 0; | |
for(int i=0; i<=reach; i++){ | |
if(reach >= A.length-1) return step; | |
max = Math.max(max, A[i]+i); | |
if(i == reach){ | |
reach = max; | |
step++; | |
} | |
} | |
return -1; | |
} | |
// this solution may cause infinite loop test case: {1, 0, 0 ,0} | |
public int jump(int[] A) { | |
if(A==null || A.length==0) return 0; | |
int max=0, temp=0, i=0, num=0; | |
while(i<A.length){ | |
if(temp>=A.length-1) break; | |
while(i<=temp){ | |
max = Math.max(i+A[i], max); | |
i++; | |
} | |
num++; | |
temp = max; | |
} | |
return num; | |
} | |
// | |
public int jump(int[] nums) { | |
if(nums == null || nums.length == 0) return 0; | |
int reach = 0, jump = 0; | |
for(int i=0; i <= reach;){ | |
if(reach >= nums.length -1) return jump; | |
int localMax = 0; | |
while(i <= reach){ | |
localMax = Math.max(localMax, i + nums[i]); | |
i++; | |
} | |
reach = localMax; | |
jump++; | |
} | |
return -1; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment