package top100liked import ( "testing" ) // https://leetcode.cn/problems/jump-game/?envType=study-plan-v2&envId=top-100-liked // 55. 跳跃游戏 // // 给你一个非负整数数组 `nums` ,你最初位于数组的 第一个下标 。数组中的每个元素代表你在该位置可以跳跃的最大长度。 // 判断你是否能够到达最后一个下标,如果可以,返回 `true` ;否则,返回 `false` 。 // 示例 1: // 输入:nums = [2,3,1,1,4] // 输出:true // 解释:可以先跳 1 步,从下标 0 到达下标 1, 然后再从下标 1 跳 3 步到达最后一个下标。 // 示例 2: // 输入:nums = [3,2,1,0,4] // 输出:false // 解释:无论怎样,总会到达下标为 3 的位置。但该下标的最大跳跃长度是 0 , 所以永远不可能到达最后一个下标。 // // 提示: // - `1 <= nums.length <= 10^4` // - `0 <= nums[i] <= 10^5` // 超时 // func canJump(nums []int) bool { // l := len(nums) // if l == 1 { // return true // } // var helper func(end int) bool // helper = func(end int) bool { // for i := range end { // if nums[i]+i >= end { // if i == 0 { // return true // } // if helper(i) { // return true // } // } // } // return false // } // return helper(l - 1) // } // canJump 判断能否到达最后一个下标。 // 思路:贪心,维护从左到右遍历时能到达的最远下标 maxReach。 // - 遍历到位置 i 时,若 maxReach < i,说明连 i 都到不了,后面更到不了 → false // - 否则更新 maxReach = max(maxReach, i + nums[i]) // - 一旦 maxReach >= 最后下标 → true // 时间 O(n),空间 O(1)。 // 超时的旧写法是自顶向下递归判断「能否到 end」,无记忆化,重复子问题导致指数级。 func canJump(nums []int) bool { maxReach := 0 for i := range nums { if maxReach < i { return false } maxReach = max(i+nums[i], maxReach) if maxReach >= len(nums)-1 { return true } } return false } func TestCanJump(t *testing.T) { cases := []struct { name string nums []int want bool }{ {"example1", []int{2, 3, 1, 1, 4}, true}, {"example2", []int{3, 2, 1, 0, 4}, false}, {"example3", []int{0}, true}, {"example4", []int{0, 1}, false}, {"example5", []int{1, 0}, true}, } for _, c := range cases { t.Run(c.name, func(t *testing.T) { got := canJump(c.nums) if got != c.want { t.Errorf("got %v, want %v", got, c.want) } }) } }