File tree Expand file tree Collapse file tree 1 file changed +28
-0
lines changed
Expand file tree Collapse file tree 1 file changed +28
-0
lines changed Original file line number Diff line number Diff line change 1+ ** 给定一个非负整数数组 nums ,你最初位于数组的 第一个下标 。数组中的每个元素代表你在该位置可以跳跃的最大长度。判断你是否能够到达最后一个下标。**
2+
3+ ```
4+ 输入:nums = [2,3,1,1,4]
5+ 输出:true
6+ 解释:可以先跳 1 步,从下标 0 到达下标 1, 然后再从下标 1 跳 3 步到达最后一个下标。
7+ ```
8+
9+ ```
10+ 我们依次遍历数组中的每一个位置,并实时维护 最远可以到达的位置。对于当前遍历到的位置 x,如果它在最远可以到达的位置 的范围内,那么我们就可以从起点通过若干次跳跃到达该位置,因此我们可以用 x+nums[x] 更新 最远可以到达的位置。
11+
12+ 在遍历的过程中,如果 最远可以到达的位置 大于等于数组中的最后一个位置,那就说明最后一个位置可达,我们就可以直接返回 True 作为答案。反之,如果在遍历结束后,最后一个位置仍然不可达,我们就返回 False 作为答案。
13+ ```
14+
15+ ```
16+ class Solution:
17+ def canJump(self, nums: List[int]) -> bool:
18+ n = len(nums)
19+ max_ind = 0
20+ for ind, num in enumerate(nums):
21+ if ind <= max_ind:
22+ cur_max_ind = ind+num
23+ if cur_max_ind > max_ind:
24+ max_ind = cur_max_ind
25+ if max_ind >= n-1:
26+ return True
27+ return False
28+ ```
You can’t perform that action at this time.
0 commit comments