Leetcode_jump-game-ii(c++ and python version)
来源:互联网 发布:淘宝怎么买电鸡 编辑:程序博客网 时间:2024/04/29 20:39
地址:http://oj.leetcode.com/problems/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.)
思路:记录当前的位置cur,和当前通过走一步能走到的最远位置farthest,下一次cur的起点是nxt
farthest赋值给nxt后,farthest更新
c++参考代码:
class Solution {public: int jump(int A[], int n) { if(n==1) return 0; int cur = 0, nxt = 0, farthest = 0, ans = 0; while(cur <= farthest) { ++ans; nxt = farthest+1; for(int i = cur; i<nxt; ++i) { if(i+A[i]>farthest) { farthest = i+A[i]; if(farthest>=n-1) return ans; } } cur = nxt; } }};
python参考代码:
class Solution: # @param A, a list of integers # @return an integer def jump(self, A): if not A or len(A)==1 : return 0 ans = cur = farthest = 0 while cur <= farthest: ans += 1 nxt = farthest + 1 for i in range(cur, nxt): if i+A[i]>farthest: farthest = i + A[i] if farthest >= len(A)-1: return ans cur = nxt
//SECOND TRIALclass Solution {public:int jump(int A[], int n) {if(n==1)return 0;if(A[0]>=n-1)return 1;int ans = 1, begin = 0, end = A[0], step = 0;while(1){while(begin<=end){step = max(step, begin+A[begin]);++begin;}if(step>=n-1)return 1+ans;begin = end;end = step;++ans;}}};
0 0
- Leetcode_jump-game-ii(c++ and python version)
- Leetcode_jump-game (updated c++ and python version)
- LeetCode_Jump Game II
- leetcode_Jump Game II
- LeetCode_Jump Game II
- LeetCode_Jump Game&&Jump Game II
- LeetCode_Jump Game
- leetcode_Jump Game
- LeetCode_jump-game
- LeetCode_Jump Game
- Leetcode_remove-duplicates-from-sorted-array-ii (c++ and python version)
- Leetcode_pascals-triangle-ii (updated c++ and python version)
- Leetcode_best-time-to-buy-and-sell-stock-ii(c++ and python version)
- 【Leetcode】【python】Jump Game/Jump Game II
- Leetcode_search-in-rotated-sorted-array-ii(updated c++ and python version)
- C. Karen and Game
- Jump Game I and II leetcode
- [leetcode] Jump Game I and II
- FreeRTOS源码分析-异常处理
- Cocos2DX 3.0新建工程
- 数据结构 第三季(part 3)
- Outlook安全钩子控件Security Manager for Microsoft Outlook介绍和下载
- uva 111 History Grading 动态规划
- Leetcode_jump-game-ii(c++ and python version)
- 给未加皮肤的EXE文件加皮肤
- 过来人经验分享:英国留学过程中如何省钱?
- jQuery插件AjaxFileUpload实现ajax文件上传时老是执行error方法 问题原因
- 黑马程序员_交通灯管理系统
- 论坛架构设计学习
- Python 引入外部自定义模块
- JDK API 中英文版 在线版、下载地址
- 使用Unity依赖注入的时候,最上层的类是Resolve还是New的问题