45. Jump Game II
来源:互联网 发布:植物学 网络 编辑:程序博客网 时间:2024/05/24 06:56
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.
Solution 1 Greedy
public static int jump(int[] nums) {int maxReach = nums[0];int minStep = 1;int edge = nums[0];for (int i = 1; i < nums.length; i++) {if (i > edge) {edge = maxReach;minStep += 1;}maxReach = Math.max(nums[i] + i, maxReach);}return nums.length == 1 ? 0 : minStep;}
Solution 2 BFS
public static int jump2(int[] nums){if(nums.length < 2){return 0;}int level = 0;int currentMax = 0;int i = 0;int nextMax = 0;while(i <= currentMax){ level++; for(;i<=currentMax;i++){ //traverse current level , and update the max reach of next level nextMax=Math.max(nextMax,nums[i]+i); if(nextMax>=nums.length-1){ return level; // if last element is in level+1, then the min jump=level } } currentMax=nextMax;}return 0;}
0 0
- 45. Jump Game II
- 45. Jump Game II
- 45. Jump Game II
- 45. Jump Game II
- 45. Jump Game II
- 45. Jump Game II
- 45. Jump Game II
- 45. Jump Game II
- 45. Jump Game II
- 45. Jump Game II
- 45. Jump Game II
- 45. Jump Game II
- 45. Jump Game II
- 45. Jump Game II
- 45. Jump Game II
- 45. Jump Game II
- 45. Jump Game II
- 45. Jump Game II
- RecyclerView基本用法:CascadeView (七)
- Easyui弹出Dialog时,Dialog中的Combobox的url会加载两次,不明原因,只能其他方法解决。
- 页面性能的基础因素 - 《Designing for Performance》
- android_activity的数据传递
- leetcode - [239] Sliding Window Maximum
- 45. Jump Game II
- Tokenization for beginners
- 设计模式之建造者模式
- 289. Game of Life
- NVIDIA GeForce Driver Installation on Debian Jessie Linux 8 64bit
- 边看书边做边发挥-图书软件-10
- c++ 去除字符串中的空格和标点符号 (remove_if 函数的用法)
- Leetcode:195. Tenth Line以及管道命令pipeline
- 162. Find Peak Element