LeetCode——No.45 Jump Game II

原始题目:

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.

题目翻译:
给出一个非负的整型数组,起跳位置在数组的第一个索引位置。(即从第一个元素开始跳)
数组中的每个元素都代表着在此元素位置最大的跳跃长度。
你的任务是用最小的跳跃次数到达数组的最后一个索引位置。
例如:
数组A=[2,3,1,1,4]
数组A到达最后一个索引位置的最小跳跃次数是2(从下标为0跳到下标为1,然后跳到最后一个索引位置)
注:假定每次都能到达最后一个索引位置。

算法思想:
用变量jumps记录跳到最后一个索引位置所要跳的次数;curEnd记录当前所能跳的最远位置(注意:不是最远距离),若curEnd大于nums.length-2则表示可以跳到最后一个索引位置或者跳过最后一个索引位置;用curFarthest记录下一跳所能跳的最远位置,其中i+num[i]表示在下标为i的位置所能跳的最远的位置。此算法运用“局部最优”和“全局最优”的思想,也可以对比BFS算法理解,总是由近及远依次遍历或比较。
算法源码:
第一种写法

class Solution {
    public int jump(int[] nums) {
        int jumps = 0, curEnd = 0, curFarthest = 0;
        for (int i = 0; i < nums.length - 1; i++) {
            curFarthest = Math.max(curFarthest, i + nums[i]);
            if (i == curEnd) {
                jumps++;
                curEnd = curFarthest;
            }
        }
        return jumps;
    }
}

第二种写法

public  int jump(int[] A) {
         if(A.length<2)return 0;
         int level=0,currentMax=0,i=0,nextMax=0;

         while(currentMax-i+1>0){       //nodes count of current level>0
             level++;
             for(;i<=currentMax;i++){   //traverse current level , and update the max reach of next level
                nextMax=Math.max(nextMax,A[i]+i);
                if(nextMax>=A.length-1)return level;   // if last element is in level+1,  then the min jump=level 
             }
             currentMax=nextMax;
         }
         return 0;
        }

算法复杂度:
两种算法的时间复杂度和空间复杂度一样。
时间复杂度:O(n) (将数组遍历一遍)
空间复杂度:O(1) (没有增加额外的空间)

猜你喜欢

转载自blog.csdn.net/wardseptember/article/details/79828681