45. Jump Game II

来源:互联网 发布:mac 下html开发工具 编辑:程序博客网 时间:2024/06/07 19:18

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

Note: You can assume that you can always reach the last index.

这题是jump game的延伸,个人觉得算是比较简单的hard题。我的粗糙想法是,跳一次,检查一次,如果此时最大可以跳到的下标达不到我们的目标(此处就是最后一个元素),再跳一次。下一个状态可以实现的最大下标,应该检索的范围是在现阶段的最大下标和上一个最大下标之间。代码如下:

int jump(vector<int>& nums) {    int i = 0, j = 0, max_idx = 0, jump = 0;    int n = nums.size();    if (n <= 1) return 0;    max_idx = max(max_idx, i + nums[i]);    jump++;    while (max_idx < n - 1) {        jump++;        int temp = max_idx;// temp和i结合记录更新前的最大下标,作为下次检索的下边界        // 在现阶段max_idx和上一个max_idx寻找新的跳动可以实现的最大下标        for (j = max_idx; j > i; j--) {            max_idx = max(max_idx, j + nums[j]);        }        i = temp;    }    return jump;}

效率为O(n)。

我的做法是先跳再检查,标准的动态规划做法就是一步步走,检查是否需要更新到下一个状态,也就是先检查再跳,或者说直到状态转移条件满足的时候再跳。其实跟我的差不多,但实际上这两题jump game都是一种动态规划的体现,需要我们明确这种思想, 也属于面试常见动态规划算法题。

int jump(vector<int>& nums) {    if(nums.size()==0)      return 0;      int lastReach = 0;      int reach = 0;      int step = 0;      for(int i=0;i<=reach&&i<nums.size();i++)      {          if(i>lastReach)  //满足转移条件就更新状态        {              step++;              lastReach = reach;          }          reach = max(reach,nums[i]+i);      }      if(reach<nums.size()-1)          return 0;      return step;  }
1 0
原创粉丝点击