跳跃游戏 I 中等🌟🌟🌟🌟🌟
课后作业
问题描述
原文链接:55. 跳跃游戏
给定一个非负整数数组 nums ,你最初位于数组的第一个下标。
数组中的每个元素代表你在该位置可以跳跃的最大长度。
判断你是否能够到达最后一个下标。
示例 1:
输入:nums = [2,3,1,1,4]
输出:true
解释:可以先跳 1 步,从下标 0 到达下标 1, 然后再从下标 1 跳 3 步到达最后一个下标。
示例 2:
输入:nums = [3,2,1,0,4]
输出:false
解释:无论怎样,总会到达下标为 3 的位置。但该下标的最大跳跃长度是 0 , 所以永远不可能到达最后一个下标。
提示:
1 <= nums.length <= 3 * 1040 <= nums[i] <= 105
代码实现
Java
class Solution {
/*
1.如果从当前位置能够跳到位置i,意味着,i前面的所有位置我们都可以到达。
2.我们要尽可能跳的远一点
3.最后我们判断,自己能否能否到达最有一个位置
*/
public boolean canJump(int[] nums) {
int max = 0;
for(int i = 0;i < nums.length; i++){
if(max < i) return false;// 连 i 这个位置都到达不了
max = Math.max(max, i + nums[i]);
}
return true;
}
}
Python
class Solution(object):
def canJump(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
max_reach = 0
for i in range(len(nums)):
if max_reach < i:
return False # 连 i 这个位置都到达不了
max_reach = max(max_reach, i + nums[i])
return True
C++
class Solution {
public:
bool canJump(vector<int>& nums) {
int max_reach = 0;
for (int i = 0; i < nums.size(); i++) {
if (max_reach < i) return false; // 连 i 这个位置都到达不了
max_reach = max(max_reach, i + nums[i]);
}
return true;
}
};
Go
func canJump(nums []int) bool {
maxReach := 0
for i := 0; i < len(nums); i++ {
if maxReach < i {
return false // 连 i 这个位置都到达不了
}
maxReach = max(maxReach, i+nums[i])
}
return true
}
func max(a, b int) int {
if a > b {
return a
}
return b
}