题目: 给你一个非负整数数组 nums ,你最初位于数组的第一个位置。
数组中的每个元素代表你在该位置可以跳跃的最大长度。
你的目标是使用最少的跳跃次数到达数组的最后一个位置。
假设你总是可以到达数组的最后一个位置。 题目链接
我的JavaScript解法
/**
* @param {number[]} nums
* @return {number}
*/
var jump = function(nums) {
let curDistance = 0 + nums[0];
let nextDistance = 0;
let jumps = 0;
for (let i = 1; i < nums.length; i++) {
nextDistance = Math.max(nextDistance, i + nums[i]);
if (curDistance >= nums.length - 1) {
jumps++;
break;
} else if (i == curDistance) {
jumps++;
curDistance = nextDistance;
}
}
return jumps;
};
解析: 贪心算法
- 时间复杂度:
- 空间复杂度: