您的位置:首页 > 其它

Jump Game(55题):贪心算法,数组

2018-02-11 13:43 211 查看
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
.

一个比较经典的游戏,给定数组判断能否到达终点。每个位置的数字表示可以往下跳跃的最大步数。如果可以到达数组最后一个元素(也可超出)则判定为true;

首先想到的是回溯算法(比较暴力),即每次达到一个位置进行循环递归,分别找出前进1,2,3,4.。。直到当前数字的步数时是否能判定通过。时间复杂度应该是指数级别的(没有仔细运算)。

第二种是贪心算法,即每次都找到局部最优解,即记录当前点能达到的距离(当前点 + 当前位置步数)较大的值。如果这个值大于或等于数组最有一个元素位置,则返回true。在此过程中如果不能到达下一个点,则返回false。

代码:

class Solution {
public boolean canJump(int[] nums) {
//考虑特殊情况
if(nums.length < 1)
return false;
if(nums.length == 1)
return true;
int whole = 0;
for(int i = 0;i < nums.length - 1;i ++){
int local = nums[i] + i;
whole = Math.max(whole,local);
//判断是否能到达下一位置
if(whole < i + 1)
return false;
//如果能到达结尾就退出
else if(whole >= nums.length - 1)
return true;
}
//无效判定,因为前面一定能结束,为了通过编译。
return true;
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  贪心算法