作者umi0912umi (大空スバル的香腸)
看板Marginalman
標題Re: [閒聊] 每日LeetCode
時間Wed Feb 8 18:21:08 2023
: 45. Jump Game II
: 給你一個陣列nums,nums[i]表示從這個點可以往後移動幾格,求出從第0格開始,最少
: 跳幾格可以跳到陣列尾端(題目保證一定可以到陣列尾端)。
:
: Example:
:
: Input: nums = [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.
:
: Input: nums = [2,3,0,1,4]
: Output: 2
class Solution:
def jump(self, nums: List[int]) -> int:
count, now_pos = 0, 0
while now_pos < len(nums)-1 :
jump_step = nums[now_pos]
max_length = 0
if now_pos + jump_step >= len(nums)-1 :
return count+1
for i in range(jump_step) :
if nums[now_pos+i+1] == 0 :
continue
else :
max_length_t = nums[now_pos+i+1] + i
if max_length_t > max_length :
max_length = max_length_t
max_i = i+1
now_pos = now_pos + max_i
count += 1
return count
看惹一下別人寫的code
跟我思路一樣可是就是乾淨好多
還有原來可以max()裡面在包for來比
我好爛
QQ
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 223.140.201.68 (臺灣)
※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1675851671.A.38B.html
推 SecondRun: 大師 02/08 18:22
推 heynui: 大師 02/08 18:23
推 pandix: 大師 02/08 18:25