45. Jump Game II

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.

解析

  • 运用bfs的思想,更新每一层的start,end,判断是否到达数组结尾,返回bfs的层数
  • 也是一种贪心的思想,
// 45. Jump Game II
class Solution_45 {
public:
    int jump(vector<int>& nums) {
        int n = nums.size(), step = 0;
        int start = 0, end = 0; //bfs每一层的开始结束位置 //每层结束更新
        while (end<n-1) //end<n时,end=n-1就可以结束了
        {
            step++;
            int maxend = end + 1; //至少走一步
            for (int i = start; i <= end;i++)
            {
                if (i+nums[i]>n)
                {
                    return step;
                }
                maxend = max(i+nums[i],maxend); //取当前这步范围内,下一步最远的位置;这里可以记录最远的那一步位置,直接start跳到那里去;
            }
            start = end + 1;
            end = maxend;
        }
        return step;
    }

    int jump(int A[], int n) {

        vector<int> vec(A,A+n);
        return jump(vec);
    }
};
public class Solution {
    public int jump(int[] nums) {
        /**
         * 本题用贪心法求解,
         * 贪心策略是在每一步可走步长内,走最大前进的步数
         */
        if(nums.length <= 1){
            return 0;
        }
        int index,max = 0;
        int step = 0,i= 0;
        while(i < nums.length){
            //如果能直接一步走到最后,直接步数+1结束
            if(i + nums[i] >= nums.length - 1){
                step++;
                break;
            }
            max = 0;//每次都要初始化
            index = i+1;//记录索引,最少前进1步
            for(int j = i+1; j-i <= nums[i];j++){//搜索最大步长内行走最远的那步
                if(max < nums[j] + j-i){
                    max = nums[j] + j-i;//记录最大值
                    index = j;//记录最大值索引
                }
            }
            i = index;//直接走到能走最远的那步
            step++;//步长+1
        }
        return step;
    }
}

题目来源

    原文作者:ranjiewen
    原文地址: https://www.cnblogs.com/ranjiewen/p/8542163.html
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞