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.
Your goal is to reach the last index in the minimum number of jumps.
Example:
Input: [2,3,1,1,4] Output: 2 Explanation: The minimum number of jumps to reach the last index is 2. Jump 1 step from index 0 to 1, then 3 steps to the last index.
Note:
You can assume that you can always reach the last index.
Solution: Greedy
Jump as far as possible but lazily.
[2, 3, 1, 1, 4] i nums[i] steps near far - - 0 0 0 0 2 0 0 2 1 3 1 2 4 2 1 1 2 4 3 1 2 4 4 4 4 2 4 8
Time complexity: O(n)
Space complexity: O(1)
C++
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
// Author: Huahua, running time: 12 ms / 10.3 MB class Solution { public: int jump(vector<int>& nums) { int steps = 0; int near = 0; int far = 0; for (int i = 0; i < nums.size(); ++i) { if (i > near) { ++steps; near = far; } far = max(far, i + nums[i]); } return steps; } }; |
请尊重作者的劳动成果,转载请注明出处!花花保留对文章/视频的所有权利。
如果您喜欢这篇文章/视频,欢迎您捐赠花花。
If you like my articles / videos, donations are welcome.
Be First to Comment