LeetCode: Jump Game II
来源:互联网 发布:2003年网络歌曲大全 编辑:程序博客网 时间:2024/05/24 04:30
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.)
class Solution {public: int jump(int A[], int n) { if(n == 0 || n == 1) return 0; if(A[0] >= n-1) return 1; int index = 0; int max = 0; int nextIndex = 0; int step = 1; while(index < n) { max = 0; nextIndex = 0; for(int i = 1; i <= A[index]; i++) { if(A[index+i] + index +i >= n-1) return step+1; if(A[index+i] + index + i > max) { max = A[index+i] + index + i; nextIndex = index+i; } } index = nextIndex; step++; } }};
Round 2:
class Solution {public: int jump(vector<int>& nums) {if(nums.size() <= 1)return 0;if(nums[0] >= nums.size()-1)return 1; int index = 0;int steps = 1;while(index < nums.size()){int maxstep = -1;int maxIndex = 0;for(int i = index+1; i <= index + nums[index]; i++){if(i + nums[i] >= nums.size()-1){return steps+1;}else{if(i + nums[i] > maxstep){maxstep = i + nums[i];maxIndex = i;}}}if(maxstep == -1)return -1;steps++;index = maxIndex;} }};
0 0
- LeetCode: Jump Game II
- LeetCode Jump Game II
- LeetCode: Jump Game II
- [Leetcode] Jump Game II
- [LeetCode] Jump Game II
- [Leetcode] Jump Game ii
- leetcode Jump Game II
- leetcode Jump Game II
- [LeetCode]Jump Game II
- [leetcode]Jump Game II
- LeetCode-Jump Game II
- [leetcode] Jump Game II
- LeetCode - Jump Game II
- LeetCode:Jump Game II
- LeetCode | Jump Game II
- 【Leetcode】Jump Game II
- LeetCode Jump Game II
- [LeetCode] Jump Game II
- 提高NodeJS网站的安全性:Web服务器防黑客攻击技巧
- ImageView 的 scaleType 小结
- 检测邮箱有效,及手机号码的一些方法
- POJ 1001 解题报告 高精度大整数乘法模版
- 毕业7天,手握8家offer,低调哥为就业支招
- LeetCode: Jump Game II
- kafka集群搭建
- asp.net微信公众平台开发
- iOS多线程GCD简介(二)
- Windows平台下LispBox环境搭建
- Xcode 6 上模拟器键盘不弹出问题
- 自动化测试学习笔记
- Linux I/O 原理
- android ListView 几个重要属性