[Greedy]45. Jump Game II

  • 分類:Greedy
  • 時(shí)間復(fù)雜度: O(n)

45. Jump Game II

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.

代碼:

方法:

class Solution:
    def jump(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        length=len(nums)
        distance=0
        biggest_step=0
        count=0
        
        for i in range(length):
            distance=max(distance,i+nums[i])
            if biggest_step!=length-1 and i==biggest_step:
                count+=1
                biggest_step=distance
                
        return count

討論:

1.挺簡(jiǎn)單的貪心算法題= 。=
2.注意biggest_step!=length-1,已經(jīng)到達(dá)終點(diǎn)了就不要count+1了

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容