博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
【一天一道LeetCode】#45. Jump Game II
阅读量:4197 次
发布时间:2019-05-26

本文共 1696 字,大约阅读时间需要 5 分钟。

一天一道LeetCode系列

(一)题目

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.

(二)解题

1、首先想到的做法就是对于序号i,判断i+nums[i]能不能到达终点,如果能直接return,如果不能对小于nums[i]的数依次进行递归,得到最小的min值。这种做法直接超时了,TLE!

class Solution {public:    int min;    int jump(vector
& nums) { min = nums.size(); jumpdfs(nums,0,0); return min; } void jumpdfs(vector
& nums , int idx , int count) { int len = nums.size(); if(idx >= len -1) { min = count; return; } if(idx
= len-1){ min = min>(count+1)?(count+1):min; return; } else { for(int i = 1 ; idx

2、然后看到提示中有提到贪心算法,于是联想到昨天做的通配符那题,可以记录上一跳能达到的最远位置,和当前跳所能到达的最远位置,每次循环就更新这两个值,直到上一跳能达到终点就退出。

/*思路:贪心算法是假定每一次都作出当前的最优解,所以对于本题,每次记录当前的最远位置,和上一跳的最远位置。*/class Solution {public:    int jump(vector
& nums) { int ret = 0 ; int last = 0; int cur = 0; for(int i = 0 ; i < nums.size() ; i++) { if(last>=nums.size()-1) break; if(i>last)//如果当前位置已经跳出了上一跳的最远位置 { last = cur;//更新上一跳的最远位置等于当前跳的最远位置 ++ret;//跳的次数加1 } cur = max(cur , i+nums[i]);//更新当前跳的最远位置 } return ret; }};

转载地址:http://jayli.baihongyu.com/

你可能感兴趣的文章
软件测试框架介绍
查看>>
软件自动化测试框架的发展
查看>>
nginx反向代理的缓存
查看>>
基于Keepalived+Haproxy+Varnish+LNMP企业级架构
查看>>
实现haproxy+LNMT负载均衡架构
查看>>
常感冒的小朋友的应对
查看>>
centos单机安装Hadoop2.6
查看>>
centos单机安装Spark1.4.0
查看>>
java - 日期相减、四舍五入
查看>>
java - mysql连接
查看>>
java - properties read write
查看>>
折腾sparkR
查看>>
Install Python 2/3 on CentOS 6.5 Server
查看>>
PySpark in PyCharm on a remote server
查看>>
virtualbox增强功能-VBoxGuestAdditions安装
查看>>
Linux下安装MySql(版本5.5以上)
查看>>
Virtualbox中Linux添加一个新磁盘
查看>>
胜景之地
查看>>
jar 独立运行文件制作(于windows平台)
查看>>
使用selenium动态爬取
查看>>