算法分析与设计week04--45.Jump Game II

来源:互联网 发布:职场女强人知乎 编辑:程序博客网 时间:2024/06/07 22:15

45.Jump Game II

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.

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

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

Analyse

思路和Jump Game类似,只是原来的全局最优现在要分成step步最优和step-1步最优(假设当前步数是step步)。当走到超过step-1步最远的位置时,说明step-1不能到达当前一步,我们就可以更新步数,将step+1。

class Solution {public:    int jump(vector<int>& nums) {        int step = 0;       //  当前步数         int lastReach = 0;  //  step-1时可达最远距离         int reach = 0;      //  step时可达最远距离         for (int i = 0; i < nums.size() && i <= reach; i++) {            if (i > lastReach) {                step++;                lastReach = reach;            }            reach = max(reach, i + nums[i]);        }         if (reach >= nums.size() - 1)             return step;    }};

复杂度分析

时间复杂度:O(n)
空间复杂度:O(1)