zoukankan      html  css  js  c++  java
  • leetcode_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.)

    思路:

    1.Jump Game思路:和求Max Subarray类似,维护一个当前元素能够跳至的最大值,每循环一次更新reach=Math.max(nums[i]+1,reach),当i>reach或i>=nums.length的时候循环终止。最后看循环是否到达了最后,到达最后则返回true,否则,返回false.

    2.和Jump Game不同的是,Jump Game II 让求的是跳过全部的元素至少须要几步。这须要维护一个局部变量edge为上一个reach,当i<=reach时,每次仍然通过Math.max(nums[i]+i,reach)获得最大的reach,当i>edge时,仅仅须要更新一个edge为当前reach就可以。并将minStep赋值为minStep+1。最后,当到达最后一个元素的时候说明能够到达最后,范围最少的步骤就可以。

    代码:

    public int jump(int[] nums)
    	{
    		int edge=0,reach=0;
    		int minStep=0,i=0;
    		for(;i<nums.length&&i<=reach;i++)
    		{
    			if(edge<i)
    			{
    				edge=reach;
    				minStep=minStep+1;
    			}
    			reach=Math.max(nums[i]+i, reach);
    		}
    		if(i==nums.length)
    			return minStep;
    		return -1;
    	}


  • 相关阅读:
    MO 中的imagelayer
    GDAL之OGR入门(转载)
    OGR体系结构
    C++与C# 以及指针
    如何用C#编程实现动态生成Word文档并填充数据?
    C++的类与C#的类[zt]
    arcmap vba 实现“卫星立体测图”高度字段值的计算,今天的一点小成就
    lib 和 dll from baidu
    ping and netstat
    Visual Basic6.0 中的类模块和标准模块
  • 原文地址:https://www.cnblogs.com/brucemengbm/p/6909980.html
Copyright © 2011-2022 走看看