Jump Game--lintcode
来源:互联网 发布:php源码测试软件 编辑:程序博客网 时间:2024/06/16 12:05
Description
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.
Example
A = [2,3,1,1,4], return true.
A = [3,2,1,0,4], return false.
我的思路:贪心算法。我开始的时候 是用i+=A[i],可是万一跳到数组中值为0的位置,就需要另外判断。是返回false,还是跳的步数少一点。很麻烦。都用到两个for循环了。网上搜索了一下。
参考网址:http://blog.csdn.net/linhuanmars/article/details/21354751
public boolean canJump(int[] A) { if(A==null || A.length==0) return false; int reach = 0; for(int i=0;i<=reach&&i<A.length;i++) { reach = Math.max(A[i]+i,reach); } if(reach<A.length-1) return false; return true; }
这里 i是一个一个加的,不是跳着的。
以2,3,1,1,4为例:
i=0 reach=max(0+2,0)=2;
i=1 reach=max(1+3,2)=4;
i=2 reach=max(2+1,4)=4;
i=3 reach=max(3+1,4)=4;
i=4 reach=max(4+4,4)=8.
返回true.
以3,2,1,0,4为例:
i=0, reach=max(0+3,0)=3;
i=1 reach=max(1+2,3)=3;
i=2 reach=max(2+1,3)=3;
i=3 reach=max(3+0,3)=3.
此时i<=reach。所以跳出for循环。而reach
- lintcode: Jump Game
- Jump Game--lintcode
- LintCode Jump Game 跳跃游戏
- [Lintcode]Jump Game跳跃游戏
- LintCode Jump Game 跳跃游戏
- [LintCode] 跳跃游戏II Jump Game II
- Jump Game
- Jump Game
- Jump Game
- Jump Game
- Jump Game
- Jump Game
- Jump Game
- Jump Game
- Jump Game
- Jump Game
- Jump Game
- Jump Game
- C++中的istringstream 的用法
- Unable to import Maven project into IntelliJ IDEA2017
- flume netcat source 监听 44444 -记flume官方文档的简单例子
- C
- java.lang.SecurityException: Requires android.permission.MOUNT_UNMOUNT_FILESYSTEMS permission
- Jump Game--lintcode
- css3自定义圆环
- 火狐浏览器中drop事件失效,event事件无作用
- MySql 常见错误
- 通过gradle实现自动切换测试环境和线上环境
- 什么是火星坐标系(GCJ-02)
- Redis超级新手指南-上篇(福禄篇)
- 【动态】浏览器与比特币:谷歌、苹果等开始采用兼容加密货币的API
- 【国际】日本金融厅批准Coincheck的比特币交易所执照