Files
leetcode/top-100-liked/79/leetcode_test.go
T
2026-07-23 16:56:50 +08:00

63 lines
1.7 KiB
Go

package top100liked
import (
"testing"
)
// https://leetcode.cn/problems/jump-game-ii/?envType=study-plan-v2&envId=top-100-liked
// 45. 跳跃游戏 II
//
// 给定一个长度为 `n` 的 0 索引整数数组 `nums`。初始位置在下标 0。
// 每个元素 `nums[i]` 表示从索引 `i` 向后跳转的最大长度。换句话说,如果你在索引 `i` 处,你可以跳转到任意 `(i + j)` 处:
// - `0 <= j <= nums[i]` 且
// - `i + j < n`
// 返回到达 `n - 1` 的最小跳跃次数。测试用例保证可以到达 `n - 1`。
// 示例 1:
// 输入: nums = [2,3,1,1,4]
// 输出: 2
// 解释: 跳到最后一个位置的最小跳跃数是 `2`。
// 从下标为 0 跳到下标为 1 的位置,跳 `1` 步,然后跳 `3` 步到达数组的最后一个位置。
// 示例 2:
// 输入: nums = [2,3,0,1,4]
// 输出: 2
//
// 提示:
// - `1 <= nums.length <= 10^4`
// - `0 <= nums[i] <= 1000`
// - 题目保证可以到达 `n - 1`
func jump(nums []int) int {
if len(nums) <= 1 {
return 0
}
mR, end, count := 0, 0, 0
for i := 0; i < len(nums)-1; i++ { // 只到 n-2,终点不需要跳
mR = max(i+nums[i], mR)
if i == end { // 当前一跳的范围扫完,结算
count++
end = mR
}
}
return count
}
func TestJump(t *testing.T) {
cases := []struct {
name string
nums []int
want int
}{
{"example1", []int{2, 3, 1, 1, 4}, 2},
{"example2", []int{2, 3, 0, 1, 4}, 2},
{"example3", []int{1}, 0},
{"example4", []int{7, 0, 9, 6, 9, 6, 1, 7, 9, 0, 1, 2, 9, 0, 3}, 2},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
got := jump(c.nums)
if got != c.want {
t.Errorf("got %v, want %v", got, c.want)
}
})
}
}