Lunski's Clutter

This is a place to put my clutters, no matter you like it or not, welcome here.

0%

55. Jump Game

Given an array of non-negative integers nums, you are initially positioned at the first index of the array.

Each element in the array represents your maximum jump length at that position.

Determine if you are able to reach the last index.

Example 1:

1
2
3
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:

1
2
3
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.
  1. We start travering the array from start.
  2. While traversing, we keep a track on maximum reachable index and
  3. update it accordingly. If we reach the maxium reachable index we get out of loop.

At last, if maxium reachable index is greater than or equal to last index of the array, means we can reach the last element else return false.

Java

1
2
3
4
5
6
7
8
9
10
11
12
T: O(n), S: O(1)
class Solution {
public boolean canJump(int[] nums) {
int reachableIndex = 0;
for(int i = 0; i<=nums.length && i<= reachableIndex;i++){
reachableIndex = Math.max(reachableIndex,i+nums[i]);
if(reachableIndex >= nums.length-1)
return true;
}
return false;
}
}

Python

1
2
3
4
5
6
7
8
9
10
11
12
T: O(n), S: O(1)
class Solution:
def canJump(self, nums: List[int]) -> bool:
reachableIndex = 0 # find maximum reachable index

for index, num in enumerate(nums):
if index + nums[index] >= reachableIndex:
reachableIndex = index + num # update reachable index
if index == reachableIndex:
break

return reachableIndex >= len(nums) - 1 # if greater than length, reachable

如果你覺得這篇文章很棒,請你不吝點讚 (゚∀゚)

Welcome to my other publishing channels