LeetCode 0055 Jump Game
作者:互联网
1. 题目描述
2. Solution
1、思路分析
遍历nums,对于nums[i]来说,能到达的最远距离为 i + nums[i],将其值保存到变量 reach中,进一步地,还需要跟上一步计算过的reach进行比较,取较大者更新reach,即 reach= max{i + nums[i], reach},在此过程中,若i > reach则立即退出循环,因为已经不可达。遍历结束后,若可达则 i应该等于nums.length。
2、代码实现
package Q0099.Q0055JumpGame;
public class Solution {
/*
I just iterate and update the maximal index that I can reach
*/
public boolean canJump(int[] nums) {
int i = 0;
for (int reach = 0; i < nums.length && i <= reach; i++)
reach = Math.max(i + nums[i], reach);
return i == nums.length;
}
}
同样的思路,从后往前推
package Q0099.Q0055JumpGame;
public class Solution2 {
// 从后往前推
public boolean canJump(int[] nums) {
int n = nums.length, last = n - 1;
for (int i = n - 2; i >= 0; i--) {
if (i + nums[i] >= last) {
last = i;
}
}
return last == 0;
}
}
3、复杂度分析
时间复杂度: O(n)
空间复杂度: O(1)
标签:last,nums,int,reach,length,public,Jump,Game,LeetCode 来源: https://www.cnblogs.com/junstat/p/16095097.html