[LeetCode][JavaScript]Jump Game II
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.)
https://leetcode.com/problems/jump-game-ii/
没有用贪心MLE和TLE....
这边解释得很好:
http://blog.sina.com.cn/s/blog_6a0e04380102v5ag.html
讨论:
https://leetcode.com/discuss/422/is-there-better-solution-for-jump-game-ii
1 /** 2 * @param {number[]} nums 3 * @return {number} 4 */ 5 var jump = function(nums) { 6 var count = 0; 7 var hasJump = 0; 8 var max = 0; 9 for(var i = 0; i < nums.length; i++){ 10 if(hasJump < i){ 11 count++; 12 hasJump = max; 13 } 14 max = Math.max(max, nums[i] + i); 15 } 16 return count; 17 18 };