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
.
对于题目一,思路很简单,贪心,只需要时刻计算前位置和当前位置所能跳的最远长度,并始终和n作比较就可以:
1,若在任意位置出现max(表示当前能跳到的最远范围) <= index 且 当前值为0,则说明无法继续向前移动,返回false
2.若在任意位置出现index + nums[index] > max,则说明能跳到更远的位置,更新max值;
3.若max >= len(nums) - 1, 说明可以完成最后一跳,返回true
Python代码如下:
class Solution(object):
def canJump(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
if nums == None or len(nums) <= 1:
return True
max = nums[0]
for i in range(len(nums)):
if max <= i and nums[i] == 0:
return False
if i + nums[i] > max:
max = i + nums[i]
if max >= len(nums) - 1:
return True
return False
Jump Game II题目描述如下:
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.
Your goal is to reach the last index in the minimum number of jumps.
For example:
Given array A = [2,3,1,1,4]
The minimum number of jumps to reach the last index is 2
. (Jump 1
step from index 0 to 1, then 3
steps to the last index.)
index+array[index]
,那么下一个区间的左端点就是当前区间的右端点+1,下一个区间的右端点就是当前区间的
max(index+array[index])
,以此类推,直到区间包含了终点,统计当前步数即可。
Python代码如下:
class Solution(object):
def jump(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if nums == None or len(nums) == 1:
return 0
begin = 0
end = 0
max_index = 0
count = 0
while max_index < len(nums) - 1:
count += 1
for i in range(begin, end + 1):
max_index = max(max_index, i + nums[i])
begin = end + 1
end = max_index
return count
以上内容参考
http://blog.csdn.net/loverooney/article/details/38455475