leetcode45 Jump Game II

我的github:https://github.com/gaohongbin/leetcode

题目:

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.)

Subscribe to see which companies asked this question

翻译:

此题跟leetcode55题相似,只是leetcode55让返回的是是否可以到达终点,而这道题让返回的是最少几步可以到达终点。


思路:

设置两个参数,一个first表示正在查找的范围能到哪里,一个sum 表示前一个范围最远能到哪里。

first初始值为nums[0].

参数i用来遍历,参数numOfJum用来记录,现在到达现在i的位置最少需要跳几次。

遍历1到first范围内的所有台阶,看第二次跳跃最远能跳到哪里赋值给sum,当i遍历到first时,修改numOfJum加1,如果sum>=length-1,则表示下次就可以到达终点,此时还需要再判断:如果此时i<=first && first<length-1则numOfJum+1,就是最终的结果。如果此时first>=length-1,则numOfJum 就是最终结果。

如果sum<length-1, 并且i==first 则numOfJum+1,first=sum;循环继续进行。


代码:

public int jump(int[] nums) {
            int length=nums.length;
	     if(length==1)
	    	 return 0;
	     
	     int first=nums[0];  //first代表第一轮能到达的最远处
	     int sum=nums[0];  //sum代表下一轮能到达的最远处
	     int numOfJum=1;
	     int i=1;
	     while(i<=first){
            	if(i+nums[i]>sum)
            		sum=i+nums[i];
            	if(sum>=length-1){
            		if(i<=first && first<length-1)
            			return ++numOfJum;
            		else
            			return numOfJum;
            	}
            	else if(i==first && first<length-1 ){
            		first=sum;
            		numOfJum++;
            	}
            	
            	i++;
	     }
	     return numOfJum;
	    }



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值