You are given an integer array nums
. You are initially positioned at the array's first index, and each element in the array represents your maximum jump length at that position.
Return true
if you can reach the last index, or false
otherwise.
Example 1:
Input: nums = [2,3,1,1,4] Output: true Explanation: Jump 1 step from index 0 to 1, then 3 steps to the last index.
Example 2:
Input: nums = [3,2,1,0,4] Output: false Explanation: You will always arrive at index 3 no matter what. Its maximum jump length is 0, which makes it impossible to reach the last index.
Constraints:
1 <= nums.length <= 104
0 <= nums[i] <= 105
Solution 1: Greedy
We use a variable
We traverse the array from left to right, for each position false
. Otherwise, the farthest position that can be reached from position
When the traversal ends, return true
directly.
The time complexity is
class Solution:
def canJump(self, nums: List[int]) -> bool:
mx = 0
for i, x in enumerate(nums):
if mx < i:
return False
mx = max(mx, i + x)
return True
class Solution {
public boolean canJump(int[] nums) {
int mx = 0;
for (int i = 0; i < nums.length; ++i) {
if (mx < i) {
return false;
}
mx = Math.max(mx, i + nums[i]);
}
return true;
}
}
class Solution {
public:
bool canJump(vector<int>& nums) {
int mx = 0;
for (int i = 0; i < nums.size(); ++i) {
if (mx < i) {
return false;
}
mx = max(mx, i + nums[i]);
}
return true;
}
};
impl Solution {
#[allow(dead_code)]
pub fn can_jump(nums: Vec<i32>) -> bool {
let n = nums.len();
let mut i: usize = 0;
while i < n {
if nums[i] as usize + i >= n - 1 {
break;
}
let mut j: usize = 1;
let mut max_step = 0;
let mut next_i: usize = 0;
// Get the next max step
while j <= nums[i] as usize {
if (i + j) as i32 + nums[i + j] >= max_step {
max_step = (i + j) as i32 + nums[i + j];
next_i = i + j;
}
j += 1;
}
if max_step == 0 {
// No further max step
return false;
}
// Otherwise, update `i` to `next_i`
i = next_i;
}
true
}
}
func canJump(nums []int) bool {
mx := 0
for i, x := range nums {
if mx < i {
return false
}
mx = max(mx, i+x)
}
return true
}
func max(a, b int) int {
if a > b {
return a
}
return b
}
function canJump(nums: number[]): boolean {
let mx: number = 0;
for (let i = 0; i < nums.length; ++i) {
if (mx < i) {
return false;
}
mx = Math.max(mx, i + nums[i]);
}
return true;
}
/**
* @param {number[]} nums
* @return {boolean}
*/
var canJump = function (nums) {
let mx = 0;
for (let i = 0; i < nums.length; ++i) {
if (mx < i) {
return false;
}
mx = Math.max(mx, i + nums[i]);
}
return true;
};
public class Solution {
public bool CanJump(int[] nums) {
int mx = 0;
for (int i = 0; i < nums.Length; ++i) {
if (mx < i) {
return false;
}
mx = Math.Max(mx, i + nums[i]);
}
return true;
}
}