Jump Game I

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.

说是贪心算法,其实就是记录数组中每个元素可以移动的最大位置。之前思路不太清晰,写代码一定要有清晰的思路啊,而且想问题应该要从多个角度去想才对。

class Solution {
public:
bool canJump(vector<int>& nums) {
int size=nums.size();
// int flag=0;
if(size==)
return ;
int maxstep=nums[];
for(int i=;i<size;i++)
{
if(maxstep==)
return ;
maxstep--;
maxstep=max(maxstep,nums[i]); }
return ; }
};

Jump Game II

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.

Your goal is to reach the last index in the minimum number of jumps.

For example:
Given array A = [2,3,1,1,4]

The minimum number of jumps to reach the last index is 2. (Jump 1 step from index 0 to 1, then 3 steps to the last index.)

Note:
You can assume that you can always reach the last index.

仍然使用贪心,只不过是要记录当前一跳所能到达的最远距离、上一跳所能达到的最远距离,和当前所使用跳数就可以了代码如下:

class Solution {
public:
int jump(vector<int>& nums) {
int len=nums.size();
int cur=;
int last=;
int res=;
for(int i=;i<len;i++)
{
if(i>cur)
return -;
if(i>last)
{
last=cur;
res++;
}
cur=max(cur,i+nums[i]);
}
return res;
}
};
  

最新文章

  1. 手把手教你玩转nginx负载均衡(一)----使用vitualBox创建虚拟机
  2. 微信红包中使用的技术:AA收款+随机算法
  3. 使用maven编译dubbo,导入eclipse(其他maven开源项目编译类似)
  4. 关于C++和C#类型比较的相关内容
  5. leetcode72. Edit Distance
  6. 树莓派 (Raspberry Pi) 是什么?普通人怎么玩?(私有云NAS也会有;上传到百度盘的功能nas也有)
  7. JavaEE Tutorials (22) - 事务
  8. java多线程Future和Callable类的解释与使用
  9. css清除浮动大全,共8种方法
  10. 安装了C
  11. Android NFC技术(三)——初次开发Android NFC你须知道NdefMessage和NdefRecord
  12. 要求必须全部重复的数据sql--想了半天才写出来的
  13. 运行maven命令的时候出现jre不正确
  14. jquery-confirm使用方法
  15. leetcode:Single Number
  16. Java中对数组的操作
  17. 一张图知道HTML5布局(图)
  18. 第二步 使用Cordova 3.0(及以上版本) 创建安卓项目(2014-6-25)
  19. ASP.NET Session 简单超实用使用总结
  20. 【剑指offer】重建二叉树

热门文章

  1. cloneNode与事件拷贝
  2. 【神仙DP】【单调队列】【模拟题】区间覆盖
  3. 后端日期类属性date 不接受string类型日期,都是没找到解决的方法,所有前端传回的string字符串都一一转化为java定义的类型
  4. httpClient需要的jar包
  5. springcloud文章推荐
  6. Maven-Dependency Mechanism
  7. 【Contest Hunter【弱省胡策】Round #0-Flower Dance】组合数学+DP
  8. 【BZOJ】1585: [Usaco2009 Mar]Earthquake Damage 2 地震伤害
  9. cocos2dx中启用lua脚本
  10. hdu 1556(线段树之扫描线)