Problem
Given an array of non-negative integers, 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:
Input: [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: [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.
Solution: Greedy
If you can jump to i, then you can jump to at least i + nums[i].
Always jump as far as you can.
Keep tracking the farthest index you can jump to.
Init far = nums[0].
far = max(far, i + nums[i])
check far >= n – 1
ex 1 [2,3,1,1,4]
1 2 3 4 5 6 7 |
i nums[i] i + nums[i] far - - - 2 0 2 2 2 1 3 4 4 2 1 3 4 3 1 4 4 4 4 8 8 |
ex 2 [3,2,1,0,4]
1 2 3 4 5 6 |
i nums[i] i + nums[i] far - - - 3 0 3 3 3 1 2 3 3 2 1 3 3 3 0 3 3 <- can not reach index 4, break |
C++
1 2 3 4 5 6 7 8 9 10 11 12 13 |
// Author: Huahua, running time 16 ms class Solution { public: bool canJump(vector<int>& nums) { const int n = nums.size(); int far = nums[0]; for (int i = 0; i < n; i++) { if (i > far) break; far = max(far, i + nums[i]); } return far >= n-1; } }; |