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 =
A =
一个比较经典的游戏,给定数组判断能否到达终点。每个位置的数字表示可以往下跳跃的最大步数。如果可以到达数组最后一个元素(也可超出)则判定为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;
}
}
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;
}
}
相关文章推荐
- 55. Jump Game 类别:贪心算法 难度:medium
- 贪心算法解决求数组最大连续和
- LeetCode-55-Jump Game(贪心)-Medium
- 55. Jump Game(贪心)
- LeetCode-55-Jump Game 贪心水题
- 算法初步--求最大子数组和【暴力|优化枚举|贪心 】求解
- 贪心算法-经典例子
- 【Java数据结构与算法04】 | 第2章--数组
- 计算数组中哪两项的和为某值[算法]
- 算法题:均分纸牌 - 贪心
- Manacher算法,回文串及后缀数组问题
- JS实现的数组全排列输出算法
- 【数据结构与算法01】数组
- 算法习题4:求子数组的最大和
- Java数据结构和算法:数组、单链表、双链表
- (一)面试金典算法:数组与字符串
- 算法(第四版)学习笔记之java实现能够动态调整数组大小的栈
- 基本算法------贪心
- Dijkstra最短路径算法[贪心]
- bzoj3289 Mato的文件管理 莫队算法 树状数组