Java AC 408ms
public class Solution { public boolean canJump(int[] A) { int n = A.length; if(n == 0){ return false; } int maxReach = 0; int i = 0; while (i < n && i <= maxReach) { maxReach = Math.max(i + A[i], maxReach); i++; if(maxReach >= n - 1){ return true; } } return false; } }
Python AC 312ms
class Solution: # @param A, a list of integers # @return a boolean def canJump(self, A): if not A: return False n = len(A) maxReach = 0 i = 0 while i < n and i <= maxReach: maxReach = max(i+A[i], maxReach) i += 1 if maxReach >= n - 1: return True return False2、Jump Game II
Java AC 460ms
public class Solution { public int jump(int[] A) { int n = A.length; if (n == 0) { return 0; } int lastMaxReach = 0; int maxReach = 0; int i = 0; int minStep = 0; while (i < n && i <= maxReach) { if (i > lastMaxReach) { lastMaxReach = maxReach; minStep++; } maxReach = Math.max(i + A[i], maxReach); i++; } return maxReach >= n - 1 ? minStep : 0; } }
Python AC 252ms
class Solution: # @param A, a list of integers # @return an integer def jump(self, A): if not A: return 0 n = len(A) maxReach = 0 lastMaxReach = 0 i = 0 count = 0 while i < n and i <= maxReach: if i > lastMaxReach: lastMaxReach = maxReach count += 1 maxReach = max(i + A[i], maxReach) i += 1 return count if maxReach >= n - 1 else 0
这个题目有点拗口,具体的分析可以参考http://obcerver.com/post/view/p/25