题目
题目链接:
https://www.nowcoder.com/practice/14abdfaf0ec4419cbc722decc709938b
思路
参考答案Java
import java.util.*;public class Solution {/*** 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可*** @param nums int整型一维数组* @return int整型*/public int minJumpStep (int[] nums) {//如果我们「贪心」地进行正向查找,每次找到可到达的最远位置,就可以在线性时间内得到最少的跳跃次数。if (nums == null || nums.length == 0) return -1;int length = nums.length;int end = 0;int maxPosition = 0;int steps = 0;for (int i = 0; i < length - 1; i++) {maxPosition = Math.max(maxPosition, i + nums[i]);if (i == end) {end = maxPosition;steps++;}}if (end < length - 1) return -1;return steps;}
}
参考答案Go
package main/*** 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可*** @param nums int整型一维数组* @return int整型*/
func minJumpStep(nums []int) int {//贪心if nums == nil || len(nums) == 0 {return -1}length := len(nums)end := 0maxPosition := 0steps := 0for i := 0; i < length-1; i++ {cur := i + nums[i]if cur > maxPosition {maxPosition = cur}if i == end {end = maxPositionsteps++}}if end < length-1 {return -1}return steps
}
参考答案PHP
<?php/*** 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可** * @param nums int整型一维数组 * @return int整型*/
function minJumpStep( $nums )
{// 贪心if($nums==null || count($nums) ==0) {return -1;}$length = count($nums);$maxPos = 0;$steps=0;$end =0;for($i=0;$i<$length-1;$i++){$cur = $i+$nums[$i];if($cur>$maxPos){$maxPos = $cur;}if($i==$end){$end = $maxPos;$steps++;}}if($end<$length-1){return -1;}return $steps;
}