【Leetcode】之 Jump Game
2016-05-09 12:00
405 查看
一.问题描述
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.
二.我的解题思路
拿到这道题,最直接的思路就是去遍历,但是很显然,这种做法的时间复杂度很高。接下来就去思考能否使用经典的算法思想去做,比如回溯法,贪心算法等等。那么针对这道题,直观的感觉是可以采用贪心算法。
采用贪心算法的关键是选取合适的贪心策略。如果在某个位置,其能到达的最远距离超过last index,而从起点也是可以到达该位置的,那么就应该返回true。
因此,在遍历数组的时候维护一个max_step变量,表示当前位置可以到达的最远距离。测试通过的程序如下:
class Solution { public: bool canJump(vector<int>& nums) { int len = nums.size(); if (len == 0) return false; if (len == 1) return true; int max_step = nums[0]; for (int i = 1; i<len - 1; i++){ if (max_step == 0) return false; max_step--; if (nums[i] >max_step) max_step = nums[i] ; if (i+max_step >= len - 1) return true; } if(max_step<len-1) return false; else return true; } };
相关文章推荐
- AndroidStudio 中的一些快捷键
- android Launcher——启动过程详解
- MAC下打开FTP服务
- SVN CornerStone的使用
- SpringBoot动态创建Bean
- Cocoapods安装步骤
- steered BRIEF
- 虚拟内存管理的作用/好处
- JPush(极光)升级到64位对我们的影响,ASIdentifierManager,advertisingIdentifier
- android Launcher——拖放功能深入研究
- Fragment 使用add 和 hide 生命周期
- 面向切面编程(AOP)的理解
- 【第四章】 资源 之 4.1 基础知识 ——跟我学spring3
- JAVA导出EXCEL实现
- Android 编程下 Touch 事件的分发和消费机制
- sping 对 hibernate进行事务管理--Annotation, xml, 大多数使用XML
- !!导致大智慧公式总是死循环的编码风格
- Android Studio gradle更新地址
- mysql函数
- 2016年5月9日11:52:54