leetcode 55 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.


1
2
3
4
5
6
7
8
9
10
11
12
13
class  {
public boolean canJump(int[] nums) {
int max = 0;
for(int i = 0; i < nums.length; i++){
if(i > max){
return false;
}
max = Math.max(max, i+nums[i]);
}
return true;

}
}
  • Using max to tag currently, the max distance we can reach.
  • Every time , we check if current max reaches the index distance, if not, return false.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
class (object):
def canJump(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
i = 0
far = 0
while i <= far:
far = max(far, i+nums[i])
if far >= len(nums)-1:
return True
i += 1
return False