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.
测试代码(python):
class Solution(object):
def canJump(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
end = 0
for i in range(len(nums)):
if end<i:
return False
end = max(end,nums[i]+i)
if end>=len(nums)-1:
return True
性能:
参考答案:
class Solution(object):
def canJump(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
pos = len(nums) - 1
for i in xrange(len(nums)-2, -1, -1):
if nums[i] + i >= pos:
pos = i
if pos == 0:
return True
return False
性能:
测试代码(c++):
class Solution {
public:
bool canJump(vector<int>& nums) {
int i = 0;
int n =nums.size();
for (int reach = 0; i < n && i <= reach; ++i)
reach = max(i + nums[i], reach);
return i == n;
}
};