LeetCode Jump Game II

来源:互联网 发布:淘宝刷到单被骗咋追回 编辑:程序博客网 时间:2024/06/05 13:37

Description:

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.)


Solution:

第一反应是DP,但是TLE。

然后考虑的是按照步数来做,但这种做法和BFS没什么区别(也就是我Jump Game I的做法)。

下一步就是如何从当前的步数选择具有代表性的点进行下一步操作呢?

假设当前的数组是这样[a1, a2, a3, b1, b2, b3, b4, b5]

a代表是我当前第a步能走到的点,b代表的是我还未走到的点。

下一步很明确,就是从a中选一个点走。为什么可以这么操作?假设a1能走到的点是[a1, b2],很明显,a2和a3是a步就能走到的,那么我真正需要更新的也就是b1和b2,同理对于a2和a3一样。所以我就应该在a中选择能够覆盖最远的点,也就是能够在b中走的最远的点,这样的贪心想法能够保证最小。


稍微感受一下,做到现在,其实很多题目(面试经常会遇到的应该就是这种路子)最naive的解法会很简单,但是各种follow up就让人受不了了。这道题目也是,DP都能想到,但是TLE,最后还是得用greedy的解法。



<span style="font-size:18px;">import java.util.*;public class Solution {public int jump(int[] nums) {int n = nums.length;if (n == 1)return 0;int step = 0;int last = 0, cur = 0;while (true) {step++;if (cur + nums[cur] >= n - 1)break;for (int i = 1; i <= nums[last] && last + i < n; i++) {int j = i + last;if (j + nums[j] >= cur + nums[cur])cur = j;}last = cur;}return step;}}</span>


0 0