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.
题意:给出一个非负数组,初始位置为数组的第一个位置。数组中的元素表示你能跳的最远距离。问是否要可以到达最后一个索引位置
思路:刚开始,用动态规划算法,用记忆化搜索提示栈越界,用循环方式的动态规划提示超时。
用贪心算法 。从第一个位置开始,并且计算从该位置所能到达的最远距离,如果大于最后一个索引,说明是可以到达最后位置 ,否则说明不可以。
代码如下:
class Solution
{
public boolean canJump(int[] nums)
{
int len = nums.length;
int curMax = nums[0];
for (int i = 0; i <= curMax; i++)
{
if (nums[i] + i >= len - 1) return true;
curMax = Math.max(curMax, nums[i] + i);
}
return false;
}

本文讨论了如何利用贪心算法解决跳跃数组问题,即在一个非负整数数组中,每次跳跃不能超过当前位置的最大跳跃长度,目标是判断是否能到达数组的最后一个位置。通过分析,发现贪心策略是最优的解决方案。

317

被折叠的 条评论
为什么被折叠?



