原题出处:https://leetcode.cn/leetbook/read/top-interview-questions-medium/xvb8zs/
解法一(python):
class Solution:
def canJump(self, nums: List[int]) -> bool:
farthest = 0
n = len(nums)
for i in range(n):
if i > farthest:
return False
farthest = max(farthest,i + nums[i])
if farthest >= n-1:
return True
return False
思路:
-
从数组的第一个位置开始,记录当前可到达的最远位置为
farthest = 0
。 -
遍历数组中每个位置
i
,如果i
可以到达且跳到的位置i+nums[i]
更远,则更新farthest = i+nums[i]
。 -
如果
farthest >= n-1
,即最远可以跳到的位置已经超过了数组最后一个位置,那么说明可以到达最后一个位置,返回true
。 -
如果在遍历完数组后仍然没有满足条件的情况,说明无法到达最后一个位置,返回
false
。
2023-07-13 start:
解法二(java):
class Solution {
public boolean canJump(int[] nums) {
int farthest = 0;
int len = nums.length;
for (int i = 0 ; i < len; i++) {
if (farthest < i) {
return false;
}
farthest = Math.max(farthest,i+nums[i]);
if (farthest >= len-1) {
return true;
}
}
return false;
}
}
思路:同解法一
end