[Swift]LeetCode45. 跳跃游戏 II | Jump Game II
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公众号:山青咏芝(shanqingyongzhi)
➤博客园地址:山青咏芝(https://www.cnblogs.com/strengthen/)
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:https://www.cnblogs.com/strengthen/p/9907513.html
➤如果链接不是山青咏芝的博客园地址,则可能是爬取作者的文章。
➤原文已修改更新!强烈建议点击原文地址阅读!支持作者!支持原创!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
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.
Example:
Input: [2,3,1,1,4] Output: 2 Explanation: 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.
Note:
You can assume that you can always reach the last index.
给定一个非负整数数组,你最初位于数组的第一个位置。
数组中的每个元素代表你在该位置可以跳跃的最大长度。
你的目标是使用最少的跳跃次数到达数组的最后一个位置。
示例:
2
1
3
说明:
假设你总是可以到达数组的最后一个位置。
16ms
1 class Solution { 2 func jump(_ nums: [Int]) -> Int { 3 if (nums.count == 0 || nums.count == 1) { return 0 } 4 5 var res = 0 6 var mi = 0 7 for e in 0...nums.count-1 { 8 if nums[e] == 0 {continue} 9 var md = 0 10 11 if e < mi {continue} 12 // print(e,mi) 13 for c in e+1...e + nums[e] { 14 if (c >= nums.count-1) { return res + 1} 15 if (c+nums[c] > md) {mi = c} 16 md = max(md,c+nums[c]) 17 18 } 19 res += 1 20 } 21 return res 22 } 23 }
80ms
1 class Solution { 2 func jump(_ nums: [Int]) -> Int { 3 4 var startIndex = 0 5 var endIndex = 0 6 var jump = 0 7 var mostFurther = 0 8 for i in 0..<nums.count-1{ 9 mostFurther = max(mostFurther, i + nums[i]) 10 11 if i == endIndex{ 12 jump += 1 13 endIndex = mostFurther 14 } 15 16 } 17 return jump 18 } 19 }
96ms
1 class Solution { 2 func jump(_ nums: [Int]) -> Int { 3 var cnt = 0, idx = 0 4 var cur = 0, pre = 0 5 while cur < nums.count - 1 { 6 cnt += 1 7 pre = cur 8 while idx <= pre { 9 cur = max(cur, idx + nums[idx]) 10 idx += 1 11 } 12 } 13 return cnt 14 } 15 }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了