给定一个非负整数数组 nums
,你最初位于数组的 第一个下标 。
数组中的每个元素代表你在该位置可以跳跃的最大长度。
判断你是否能够到达最后一个下标。
输入:
nums = [2,3,1,1,4]
输出:
true
解释:
可以先跳 1 步,从下标 0 到达下标 1, 然后再从下标 1 跳 3 步到达最后一个下标。
输入:
nums = [3,2,1,0,4]
输出:
false
解释:
无论怎样,总会到达下标为 3 的位置。但该下标的最大跳跃长度是 0 , 所以永远不可能到达最后一个下标。
impl Solution {
pub fn can_jump(nums: Vec<i32>) -> bool {
let n = nums.len();
let mut right_most = 0usize;
for (i, v) in nums.into_iter().enumerate() {
if i <= right_most {
// 最远能跳到哪里
right_most = right_most.max(i + v as usize);
if right_most >= n - 1 {
return true;
}
}
}
return false;
}
}
func canJump(nums []int) bool {
n := len(nums)
rightMost := 0
for i, v := range nums {
if i <= rightMost {
// 最远能跳到哪里
if rightMost < i+v {
rightMost = i + v
}
if rightMost >= n-1 {
return true
}
}
}
return false
}
class Solution {
public:
bool canJump(vector<int>& nums) {
const int n = nums.size();
int rightMost = 0;
for (int i = 0; i < n; ++i) {
if (i <= rightMost) {
rightMost = max(rightMost, i + nums[i]);
if (rightMost >= n - 1) {
return true;
}
}
}
return false;
}
};
class Solution:
def canJump(self, nums: List[int]) -> bool:
n, right_most = len(nums), 0
for i in range(n):
if i <= right_most:
right_most = max(right_most, i + nums[i])
if right_most >= n - 1:
return True
return False
class Solution {
public boolean canJump(int[] nums) {
final int n = nums.length;
int rightMost = 0;
for (int i = 0; i < n; ++i) {
if (i <= rightMost) {
rightMost = Math.max(rightMost, i + nums[i]);
if (rightMost >= n - 1) {
return true;
}
}
}
return false;
}
}
非常感谢你阅读本文~
欢迎【点赞】【收藏】【评论】~
放弃不难,但坚持一定很酷~
希望我们大家都能每天进步一点点~
本文由 二当家的白帽子:https://le-yi.blog.csdn.net/ 博客原创~