November 13, 2023

Viiisit [LeetCode] - 45. Jump Game II

#javascript#ruby

keep learning, keep coding!

Problem - Jump Game II

You are given a 0-indexed array of integers nums of length n. You are initially positioned at nums[0].

Each element nums[i] represents the maximum length of a forward jump from index i. In other words, if you are at nums[i], you can jump to any nums[i + j] where:

0 <= j <= nums[i] and
i + j < n
Return the minimum number of jumps to reach nums[n - 1]. The test cases are generated such that you can reach nums[n - 1].

翻譯蒟蒻

找出從數組的第一個元素開始,按照每個元素所允許的最大跳躍步數,最終到達數組最後一個元素所需的最小跳躍次數。


Solution - JavaScript

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
/**
* @param {number[]} nums
* @return {number}
*/
var jump = function(nums) {
let currentPosition = 0;
let maxPosition = 0;
let steps = 0;

for (let i = 0; i < nums.length - 1; i++) {
// 在當前跳躍範圍內,更新能夠跳躍到的最遠位置
maxPosition = Math.max(maxPosition, i + nums[i]);

// 如果到達當前跳躍的最遠位置,更新下一個跳躍的最遠位置
if (i === currentPosition) {
currentPosition = maxPosition;
steps++;
}
}

return steps;
};

Solution - Ruby

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
def jump(nums)
current_position = 0
max_position = 0
steps = 0

# 使用迴圈遍歷 nums 中的元素,只迭代到倒數第二個元素
(nums.length - 1).times do |i|
current_position = [current_position, i + nums[i]].max
if i == max_position
max_position = current_position
steps += 1
end
end

steps
end

LeetCode 傳送門 - Jump Game II