LeetCode45跳躍遊戲二
阿新 • • 發佈:2018-11-11
題目描述:
給定一個非負整數陣列,你最初位於陣列的第一個位置。
陣列中的每個元素代表你在該位置可以跳躍的最大長度。
你的目標是使用最少的跳躍次數到達陣列的最後一個位置。
示例:
輸入: [2,3,1,1,4]
輸出: 2
解釋: 跳到最後一個位置的最小跳躍數是 2。
從下標為 0 跳到下標為 1 的位置,跳 1 步,然後跳 3 步到達陣列的最後一個位置。
說明:
假設你總是可以到達陣列的最後一個位置。
解題思路:
方法一:
這是一個超時的方法。
思路是,這個陣列,從後往前,對於最後一個元素,從他之前的陣列片段中從頭到尾遍歷,當找到能走到最後一個元素的時候,步長增加1,並將當前元素作為下一次迴圈的最後元素。直到從後往前遍歷到第一個元素為止。演算法結束。
這個方法,當步長全為1的時候,是最差,演算法複雜度達到 。演算法Python實現如下:
def jump (nums):
"""
:type nums: List[int]
:rtype: int
"""
last = len(nums) - 1
step = 0
while last > 0:
for i in range(last):
if nums[i] >= (last - i):
step = step + 1
last = i
break
return step
方法二:
從前向後遍歷,在某個節點時,計算當前節點可到達的所有的節點的計算值,這個計算值是由節點index及節點儲存值組成,即value = index + nums[index]
,計算得到最大值之後,步長+1,如果value還未到達陣列末尾,則將最大值處作為開始,再向後計算。直到能夠到達資料末尾。
GitHub地址為:https://github.com/zhangdianlei/LeetCode_python/blob/master/src/c42.py
Python程式碼實現如下:
def jump(nums):
"""
:type nums: List[int]
:rtype: int
"""
last = len(nums) - 1
step = 0
index = 0
if len(nums) == 1:
return 0
while index + nums[index] < last:
step = step + 1
max = 0
maxIndex = 0
for i in range(1, nums[index] + 1):
temp = i + index
if temp + nums[temp] >= max:
max = temp + nums[temp]
maxIndex = temp
index = maxIndex
return step + 1