zoukankan      html  css  js  c++  java
  • Java for LeetCode 045 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.)

    解题思路:

    题目不难,只需每次找出向右的最大范围的指针maxStepIndex即可,为了减少遍历,可以用一个指针start维护每次遍历的起始位置,JAVA实现如下:

    static public int jump(int[] nums) {
            int result=0,index=0,maxStepIndex=0,start=0;
        	if(nums.length>1&&0+nums[0]>=nums.length-1)
        		return 1;
            while(index<nums.length-1){
            	result++;
            	for(int i=start;i<=index+nums[index];i++){
            		if(i+nums[i]>=nums.length-1)
            			return result+1;	
            		if(i+nums[i]>=nums[maxStepIndex]+maxStepIndex)
            			maxStepIndex=i;
            	}
            	start=index+nums[index]+1;
            	index=maxStepIndex;	
            }
            return 0;
        }
    
  • 相关阅读:
    【二分】Pair of Topics
    【Windows】制作登录界面
    【Windows】制作文本框
    【windows】制作幸运“Tiger”机
    【python】函数
    SPOJ 3267 DQUERY
    CF 570D Tree Requests
    UVa 11809 Floating-Point Numbers
    Luogu P5098 Cave Cows 3
    GHOJ 428 未出现的子串
  • 原文地址:https://www.cnblogs.com/tonyluis/p/4504212.html
Copyright © 2011-2022 走看看