File tree Expand file tree Collapse file tree 3 files changed +36
-0
lines changed Expand file tree Collapse file tree 3 files changed +36
-0
lines changed Original file line number Diff line number Diff line change 1+ ``` python
2+ def canJump (nums ):
3+ n = len (nums)
4+ max_reach = 0
5+
6+ for i in range (n):
7+ if i > max_reach:
8+ return False
9+ max_reach = max (max_reach, i + nums[i])
10+
11+ return True
12+ ```
13+
14+ 1 . 首先获取输入数组 ` nums ` 的长度 ` n ` 。
15+ 2 . 初始化 ` max_reach ` 变量,用于记录当前可以到达的最远位置。
16+ 3 . 遍历数组 ` nums ` ,对于每个位置 ` i ` :
17+ - 如果 ` i ` 大于当前的 ` max_reach ` ,说明无法到达该位置,返回 ` False ` 。
18+ - 更新 ` max_reach ` 为当前 ` max_reach ` 和 ` i + nums[i] ` 的最大值。
19+ 4 . 如果能遍历完整个数组,说明可以到达最后一个位置,返回 ` True ` 。
20+
21+ 这个解决方案的时间复杂度为 O(n),空间复杂度为 O(1),因为我们只使用了一个额外的变量 ` max_reach ` 。
22+
23+ 你可以将这个函数用在你的代码中,测试一下它的正确性。如果你有任何其他问题,欢迎随时询问我。
Original file line number Diff line number Diff line change 1+ def canJump (nums ):
2+ n = len (nums )
3+ max_reach = 0
4+
5+ for i in range (n ):
6+ if i > max_reach :
7+ return False
8+ max_reach = max (max_reach , i + nums [i ])
9+
10+ return True
Original file line number Diff line number Diff line change 11from typing import List
2+ """
3+ 换钱。
24
5+ """
36class Solution :
47 def coinChange (self , coins : List [int ], amount : int ) -> int :
58 if amount == 0 :
You can’t perform that action at this time.
0 commit comments