Jump Game
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.
1 | Example 1: |
Greedy solution
I try to solve this problem by greedy solution by myself but I failed. One solution is to use greedy method.
First, we initiate a variable called maxReach, which means how far can we jump from a specific index.
Then, we iterate the loop, in each iteration, we compare if the index is larger than the maxReach, if so, it means it cannot jump to the current index, we return false.
1 | if (i > maxReach) |
Then we find the max value between maxReach
and i + nums[i]
, the larger one will be the new value of maxReach
1 | maxReach = max (maxReach, i + nums[i]); |
If the vlaue of maxReach is larger than the length of the array, which means we can jump to the end of the array, we return true.
1 | if (maxReach >= n - 1) |
Full code
1 | class Solution { |
Jump Game II
You are given a 0-indexed array of integers nums of length n. You are initially positioned at nums[0].
Each element nums[i] represents the maximum length of a forward jump from index i. In other words, if you are at nums[i], you can jump to any nums[i + j] where:
1 | 0 <= j <= nums[i] and |
1 | Example 1: |
Greedy solution
In this solution, we create a new vairable called currentPosition
. When its value is equal to the index in the loop, it means a jump is needed, so we increase the count, and update the currentPosition to the maxJump, which means we need to jump when the index is equal to the current maxJump. Also, during the iteration, we update the maxJump by comparing the current maxJump with (i+nums[i]).
1 | class Solution { |