博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[leetcode-45-Jump Game II]
阅读量:6253 次
发布时间:2019-06-22

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

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.

思路:

自己思路比较混乱,。

This problem has a nice BFS structure. Let's illustrate it using the example nums = [2, 3, 1, 1, 4] in the problem statement. We are initially at position 0. Then we can move at most nums[0] steps from it. So, after one move, we may reach nums[1] = 3 or nums[2] = 1. So these nodes are reachable in 1 move. From these nodes, we can further move to nums[3] = 1 and nums[4] = 4. Now you can see that the target nums[4] = 4 is reachable in 2 moves.

Putting these into codes, we keep two pointers start and end that record the current range of the starting nodes. Each time after we make a move, update start to be end + 1 and end to be the farthest index that can be reached in 1 move from the current [start, end].

To get an accepted solution, it is important to handle all the edge cases. And the following codes handle all of them in a unified way without using the unclean if statements :-)

int jump(vector
& nums){ if(nums.size() <= 1) return 0; int res = 0; int index = 0; int start = 0; while(index< nums.size()-1) { res++; int maxIndex = index+1; for(int i = start;i<=index;i++) { if(i + nums[i] >= nums.size()-1) return res; maxIndex = max(maxIndex,i + nums[i]); } start = index+1; index = maxIndex; } return res;}

 参考:

转载于:https://www.cnblogs.com/hellowooorld/p/6771097.html

你可能感兴趣的文章
11月20日学习内容整理:jquery插件
查看>>
预科班第四次考核总结
查看>>
【js】再谈移动端的模态框实现
查看>>
html
查看>>
Java变量类型
查看>>
[leetcode-89-Gray Code]
查看>>
mysql 存储过程的基本语法知识
查看>>
数据分析师到底在做什么?
查看>>
pt-heartbeat工具监控MySQL复制延迟
查看>>
指尖下的js —— 多触式web前端开发之三:处理复杂手势(转)
查看>>
spring boot项目配置文件集合
查看>>
cube-ui的用法
查看>>
2015.4.21 SetWindowPos函数用法
查看>>
2011-12-14 调用cmd并获得输入输出+网络访问
查看>>
解决nim db_mysql could not load: libmysql.dll的问题
查看>>
JavaScript之再谈回调与闭包
查看>>
优化PHP代码的一些建议
查看>>
android学习网站
查看>>
TCP定时器详解
查看>>
if判断,switch语句
查看>>