【leetcode】jump-game-ii

题目描述

给出一个非负整数数组,你最初在数组第一个元素的位置,数组中的元素代表你在这个位置可以跳跃的最大长度,你的目标是用最少的跳跃次数来到达数组的最后一个元素的位置。例如,给出数组 A =[2,3,1,1,4],最少需要两次才能跳跃到数组最后一个元素的位置。(从数组下标为0的位置跳长度1到达下标1的位置,然后跳长度3到数组最后一个元素的位置)

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 is2. (Jump1step from index 0 to 1, then 3 steps to the last index.)

问题分析

       从某一个位置i起跳,最远可以跳到位置A[i]+i,那么到位置i+1~i+A[i]中的任意位置只需要跳一步,只需要求解一个位置,满足跳到该位置后起跳可以跳到最远距离。该问题可以划分为一个个子问题,通过获取子问题的最优解,求解最远距离,获取整体最优解。

算法分析

该问题可以通过贪心思想得到整体最优解。通过求解局部最优解即求解局部跳最远距离,获得最少跳跃次数。对于位置i,可以跳跃到i+A[i],定义i+A[i]为cur。那么在i+1到cur范围内,求解该范围内起跳所能跳的最大值。通过last变量记录跳到最远距离,与当前位置进行比较,如果小于当前位置,那么置为当前所能跳的最远距离cur,跳跃次数加1。算法的时间复杂度为O(n)。

编码实现

public class Solution {
    public int jump(int[] A) {
        int cur=0;  
        int last=0;  
        int step=0; 
        for(int i=0; i<A.length && cur>=i; i++)
        {
            if(i>last)
            {
                last=cur;
                step++;
            }
            cur =cur>(A[i]+i)?cur:(A[i]+i);
        }
        return step;
	}
}

猜你喜欢

转载自blog.csdn.net/VinWqx/article/details/104909577