★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公衆號:山青詠芝(shanqingyongzhi)
➤博客園地址:山青詠芝(https://www.cnblogs.com/strengthen/)
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:http://www.javashuo.com/article/p-sncsfxnq-me.html
➤若是連接不是山青詠芝的博客園地址,則多是爬取做者的文章。
➤原文已修改更新!強烈建議點擊原文地址閱讀!支持做者!支持原創!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★html
Given an array of non-negative integers, you are initially positioned at the first index of the array.git
Each element in the array represents your maximum jump length at that position.github
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:spa
You can assume that you can always reach the last index.code
給定一個非負整數數組,你最初位於數組的第一個位置。htm
數組中的每一個元素表明你在該位置能夠跳躍的最大長度。blog
你的目標是使用最少的跳躍次數到達數組的最後一個位置。遊戲
示例:
輸入: [2,3,1,1,4] 輸出: 2 解釋: 跳到最後一個位置的最小跳躍數是 。 從下標爲 0 跳到下標爲 1 的位置,跳 步,而後跳 步到達數組的最後一個位置。 213
說明:
假設你老是能夠到達數組的最後一個位置。
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 }