leetcode面试准备: Jump Game II

1 题目

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.
For example:
Given array A = [2,3,1,1,4]
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.)
接口: public int jump(int[] A);

2 思路

从数字的0位置,开始往后挑,求能够达到最后一个元素的最小跳数。

贪心思想:和Jump Game类似,
maxReach表示能够走到的最远的index,不断更新这个全局最值。所以,有局部最值
局部最值: maxLocal = A[i] + i,表示走到i层时,能够达到的最远的index。
step: 走到当前的最小步数
lastReach: 关键变量的引入,在0——lastReach之间的层数,都不会增加step的步数。如何更新这个值成了问题的关键—— 遍历的层数i > lastReach的时候。
复杂度: Time:O(n) Space: O(1)

3 代码

	public int jump(int[] A) {
		int len = A.length;
		int step = 0, lastReach = 0, maxReach = 0;
		for (int i = 0; (i <= maxReach) && (i < len); i++) {
			int localReach = A[i] + i;
			if (i > lastReach) {
				step++;
				lastReach = maxReach;
			}
			maxReach = maxReach > localReach ? maxReach : localReach;
		}
		return maxReach < len - 1 ? 0 : step;
	}

4 总结

贪心的思想,从Jump Game得到思路:采用局部最值和全局最值。同时增加2个变量来获取最终的结果是关键。

5 扩展

Jump Game

6 参考

原文地址:https://www.cnblogs.com/byrhuangqiang/p/4701192.html