原题:
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.
大致题意:
给定一组非负整数数组,从数组第一个位置开始跳,你所在位置的数就是每次跳跃能前进的最多长度。求最少多少次跳跃能跳到最后一个下标,假设解存在。
跟 Jump Game I 基本一样,都可以用贪心或者动态规划解决。贪心的思路简单地说是:遍历一遍数组,不断比较当前下标位置能跳到的最远下标与之前遍历过程中记录的最远下标位置。如果当前下标超过了之前记录的位置,跳跃次数+1。返回条件就是当前能达到的最远位置>=最大下标值,则返回当前记录的跳跃次数,一定是最小值。
class Solution {
public:
int jump(vector<int>& nums) {
int ans = 0, curMax = 0, lastMax = 0;
for (int i = 0; i < nums.size() && curMax < nums.size() - 1; i++) {
if (i > curMax) {
curMax = lastMax;
ans++;
}
lastMax = max(lastMax, i + nums[i]);
}
return ans;
}
};
原题地址:https://leetcode.com/problems/jump-game-ii/description/
老实说,我觉得这题面试基本不会考。。做着玩吧