跳完数组的最少跳数

跳完数组的最少跳数

问题

这个题目说的是,给你一个非负整数数组,数组中的每个数字表示那个位置上可以向后跳的最大步数。一开始你站在下标为 0 的位置,你要计算出最少需要跳几次才能到达数组最后位置。如果无法到达数组最后位置,则返回 -1。

比如说,给你的数组 a 是:

2, 4, 0, 1, 2

一开始站在下标为 0 的位置,最多能向后跳 2 步。你先跳 1 步,来到 4,再跳 3 步就到达最后的位置。需要的最少跳数是 2。

再比如说,给你的数组是:

2, 1, 0, 4

一开始如果跳 2 步,到达 0,不能再跳。一开始如果跳 1 步,到达 1,可以向后再跳 1 步。但跳 1 步后仍然到达 0,不能再跳。因此对于这个数组,你没办法跳到最后的位置,返回 -1。

代码

public class AlgoCasts {

  // Time: O(n), Space: O(n)
  public int numOfJumpToLast(int[] nums) {
    if (nums == null || nums.length == 0) return -1;
    int n = nums.length, max = 0;
    int[] d = new int[n];
    for (int i = 0; i < n; ++i) {
      if (max >= n-1) return d[n-1];
      if (i > max) return -1;
      max = Math.max(max, i+nums[i]);
      int last = Math.min(max, n-1);
      for (int j = last; j > i && d[j] == 0; --j)
        d[j] = d[i] + 1;
    }
    return -1;
  }

  // Time: O(n), Space: O(1)
  public int numOfJumpToLastO1(int[] nums) {
    if (nums == null || nums.length == 0) return -1;
    if (nums.length == 1) return 0;
    int n = nums.length, max = 0, jumps = 0, curEnd = 0;
    for (int i = 0; i < n; ++i) {
      if (max >= n-1) return jumps + 1;
      if (i > max) return -1;
      if (i > curEnd) {
        ++jumps;
        curEnd = max;
      }
      max = Math.max(max, i+nums[i]);
    }
    return -1;
  }

}

  转载请注明: ForwardXu 跳完数组的最少跳数

 上一篇
Java并发 Java并发
Java并发 一、线程状态转换 新建(New) 可运行(Runnable) 阻塞(Blocking) 无限期等待(Waiting) 限期等待(Timed Waiting) 死亡(Terminated) 二、使用线程 实现 Runnabl
2018-12-24
下一篇 
数组的全排列 数组的全排列
数组的全排列问题 这个题目说的是,给你一个整数数组,并且数组中没有重复元素,你要返回这个数组所有可能的排列。 比如说给你的数组是: 0, 1, 2 你要返回的所有排列是: 0, 1, 2 0, 2, 1 1, 0, 2 1, 2, 0
2018-12-16
  目录