[LeetCode] Jump Game II
2015-07-15 21:30
363 查看
This problem has a nice BFS structure. Let's illustrate it using the example
Putting these into codes, we keep two pointers
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
C++
Python
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] = 3or
nums[2] = 1. So these nodes are reachable in
1move. From these nodes, we can further move to
nums[3] = 1and
nums[4] = 4. Now you can see that the target
nums[4] = 4is reachable in
2moves.
Putting these into codes, we keep two pointers
startand
endthat record the current range of the starting nodes. Each time after we make a move, update
startto be
end + 1and
endto be the farthest index that can be reached in
1move 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
ifstatements :-)
C++
class Solution { public: int jump(vector<int>& nums) { int n = nums.size(), step = 0, start = 0, end = 0; while (end < n - 1) { step++; int maxend = end + 1; for (int i = start; i <= end; i++) { if (i + nums[i] >= n - 1) return step; maxend = max(maxend, i + nums[i]); } start = end + 1; end = maxend; } return step; } };
Python
class Solution: # @param {integer[]} nums # @return {integer} def jump(self, nums): n, start, end, step = len(nums), 0, 0, 0 while end < n - 1: step += 1 maxend = end + 1 for i in range(start, end + 1): if i + nums[i] >= n - 1: return step maxend = max(maxend, i + nums[i]) start, end = end + 1, maxend return step
相关文章推荐
- CSS 优化
- C/C++字符串转换为整型
- 黑马程序员-OC语言基础:Foundation框架小结
- Angularjs,WebAPI 搭建一个简易权限管理系统 —— Angularjs 前端主体结构(五)
- 静态链接库(lib)、动态链接库(dll)与动态链接库的导入库(lib)
- 【Cocos2d-x】之C++和Lua的调用_01
- X264的ARMV7-a的交叉编译及优化运行
- LeetCode_103 Binary Tree Zigzag Level Order Traversal
- sysfs--初窥门径
- Spring MVC工作流程图
- 黑马程序员-OC语言基础:block
- 请注意SimpleDateFormat不是线程安全的
- day01--Java基础语法--Java语言基础
- iOS开发常用的第三方类库
- 使用openssl库实现RSA、AES数据加密
- Java程序与串口的通信实现及调试
- 黑马程序员-OC语言基础:内存管理
- 黑马程序员-OC语言基础:协议
- CMarkup类在VC中的使用
- cxGrid如何动态创建Items的Editor的项?