[LeetCode] 45. Jump Game II

有点意思,比想的要难。

错误思路

from  typing import List
from collections import Counter
import time


class Solution:
    def jump(self, nums: List[int]) -> int:
        max_reachable = 0
        min_steps = 0

        for i, element in enumerate(nums):
            if i > max_reachable:
                return 0
            if max_reachable >= len(nums) -1:
                return min_steps
            if (i + element) > max_reachable:
                max_reachable = i + element
                min_steps += 1
def main():
    start_time = time.time()
    print(Solution().jump([7,0,9,6,9,6,1,7,9,0,1,2,9,0,3]))
    end_time = time.time()
    print("Time taken: {:.6f} seconds".format(end_time - start_time))

if __name__ == '__main__':
    main()


正确方法

只需要在上次移动的时候更新最大可达范围和更新step即可,没有达到上一步的边界就不要动step。

class Solution:
    def jump(self, nums: List[int]) -> int:
        max_reachable = 0
        min_steps = 0
        current_edge = 0

        for i, element in enumerate(nums[:-1]):
            if i > max_reachable:
                return 0
            max_reachable = max(i + element, max_reachable)
            #update steps only when meet the edge of current movement
            if i == current_edge:
                current_edge = max_reachable
                min_steps += 1
        return min_steps

image

posted @ 2024-07-03 19:23  夜歌乘年少  阅读(2)  评论(0编辑  收藏  举报