Leetcode45. Jump Game II
来源:互联网 发布:mac os系统安装教程 编辑:程序博客网 时间:2024/06/05 02:23
题目
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,2,3,4,5][1,1,1,1,1,1,1,1][1]
代码
package leetcodeArray;public class Leetcode45JumpGameII { public int jump(int[] nums) { int i = 0, j = 1, steps = 0, n = nums.length; while(j < n){ int endj = Math.min(nums[i] + i + 1, n); while(j < endj){ if(nums[j] + j > nums[i] + i ) i = j; j++; } System.out.println(endj); steps++; } return steps; }}
运行结果
他山之玉
int jump(int A[], int n) { if(n<2)return 0; int level=0,currentMax=0,i=0,nextMax=0; while(currentMax-i+1>0){ //nodes count of current level>0 level++; for(;i<=currentMax;i++){ //traverse current level , and update the max reach of next level nextMax=max(nextMax,A[i]+i); if(nextMax>=n-1)return level; // if last element is in level+1, then the min jump=level } currentMax=nextMax; } return 0; }
class Solution {public: int jump(int A[], int n) { vector<int> track(n, 0); for(int i=1; i<n; i++){ int min = INT_MAX; for(int j=0; j<i; j++){ if(track[j] < min && A[j]+j >= i) min = track[j]; } track[i] = min+1; } return track[n-1]; }};
阅读全文
0 0
- [LeetCode45]Jump Game II
- Leetcode45 Jump Game II
- leetcode45 Jump Game II
- LeetCode45. Jump Game II
- LeetCode45. Jump Game II
- leetcode45. Jump Game II
- Leetcode45. Jump Game II
- LeetCode45. Jump Game II
- LeetCode45 Jump Game II【贪心】
- LeetCode45——Jump Game II
- Jump Game &Jump Game II
- Jump Game/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
- WIN10安装LINUX子系统教程
- 模板方法模式
- NYOJ 219-An problem about date
- 谷歌最新开源Tensor2Tensor
- Unity的WWW类的用法整理
- Leetcode45. Jump Game II
- 生成变量时自动加上m前缀
- mysql的视图使用
- 动态创建的CButton按钮,在设置字体时为什么不显示
- Maven的详解
- xilinx zynq-702 虚拟窗口
- 针对血液有关问题感想
- Unity如何使用WWW类和协程完成图片、视频下载播放
- js监听页面到底部