[Leetcode] 45. Jump Game II 解题报告

来源:互联网 发布:java 键值对会覆盖 编辑:程序博客网 时间:2024/05/16 02: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.

思路

本质上是一道用贪心算法解决的题目,但是从实现上来看却感觉是动态规划的变种:我们维护一个当前可以到达的最远位置,以及一个一维数组(记录从首元素跳到该位置元素所需的最少步数),然后遍历nums中的每个元素,一旦通过它可以跳到更远的位置,则更新当前最远位置到更远位置之间的最少步数。一旦发现最远位置到达末尾或者越界,则可以立即返回。

我感觉对本题目的时间复杂度分析可能是面试官感兴趣的另一考点:虽然从实现上来看,里面存在两重循环,但实际的时间复杂度却是O(n)。这是因为:在我们对nums中的元素做遍历的过程中,所有更新的区间是不重合的,而且这些区间刚好完整覆盖了整个数组空间,所以总和是n。

代码

class Solution {public:    int jump(vector<int>& nums)     {        if(nums.size() == 0)            return 0;        vector<int> step(nums.size(), 0);        int max_reach = 0;        for(int i = 0; i < nums.size(); ++i)        {            int tem = nums[i] + i;                          // the maximum index one can reach from i            if(max_reach < tem)            {                tem = min(tem, (int)nums.size() - 1);       // avoid overflow                for(int j = max_reach + 1; j <= tem; ++j)   // we can reach [max_reach + 1, tem] in fewer steps                    step[j] = step[i] + 1;                max_reach = tem;                if(max_reach >= nums.size() -1)             // we alrady reach the last element                    break;            }        }        return step[nums.size() - 1];    }};


0 0
原创粉丝点击