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
.
这个题,,哎呀,光弄懂题的意思已经用了洪荒之力了。。。。
大概意思是:每个位置上的元素的值代表它能跳到的最远距离,比如数组A = [2,3,1,1,4]中的A[0]=2,代表最远可以跳两步,到A[2];每跳一步,就比较该位置上的元素可以跳的最远步数,选择最大的继续跳,判断可不可以跳到最后一个元素
这个题用的是贪心算法的思想,局部最优解就是整体最优解。
详细以A = [2,3,1,1,4]
为例,A[0]时,最多可以跳两步,记做step
=2,先走到A【1】,那么可跳步数step变成了1,A【1】最多可以跳三步,取这两个的最大值,即step = 3;继续向右跳,在这个过程中右面的每个元素的最大可跳步数只要比当前剩余的可跳步数小,就不考虑,继续跳。直到判断可不可以跳到最后。
public class Solution {
public boolean canJump(int[] nums) {
if (nums.length <= 1) {
return true;
}
int step = nums[0];
for (int i = 1; i < nums.length; i++) {
if (step > 0) {
step--;
step = Math.max(step, nums[i]);
}
else {
return false;
}
}
return true;
}
}
下面另一种解法:感觉这个解法没有上面的好理解,还是用上面的吧
public class Solution {
public boolean canJump(int[] nums) {
if (nums.length <= 1) {
return true;
}
int reach = 0;
int i = 0;
for (; i < nums.length && i<= reach; i++) {//加了一个i<=reach判断i要是超过了最大跳数能到达的距离就不用判断了。
reach = Math.max(reach, i+nums[i]);//不然会一直循环到最后一个元素
}
return (i == nums.length);//所以最后结果只要返回比较结果就好了
}
}
补充:
这是刷题以来第一次接触贪心算法,好像以前做过一道选择题问贪心算法不能解决下面哪个问题。。刚看了下书,一般用贪心算法解决的问题大概有三个:1.调度问题(一个或多个处理器,多个作业以及每个作业的运行时间,求最优调度,即所有作业平均运行时间最短) 2.哈夫曼编码(一般用于文件压缩) 3.近似装箱问题