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.
Example 1
1 | Input: [2,3,1,1,4] |
Example 2
1 | Input: [3,2,1,0,4] |
解题思路
- 法一。首先想到动态规划。能否从位置
i到达末尾,取决于能否从位置i+1至i+nums[i]到达末尾,因此需要从后往前确定每个位置能否到达末尾并记录之。 - 法二。如果某个位置能够到达末尾,那么在该位置之前,只需要能够到达该位置即可。因此,可以将目标位置往前移动,使其靠近起点。若目标位置与起点重合,输出为真;否则输出为假。
复杂度分析
法一。
时间复杂度:$O(n^2)$
空间复杂度:$O(n)$
法二。
时间复杂度:$O(n)$
空间复杂度:$O(1)$
代码
1 | class Solution1 { |