日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

leetcode_Jump Game II

發布時間:2025/5/22 40 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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;}

轉載于:https://www.cnblogs.com/brucemengbm/p/6909980.html

總結

以上是生活随笔為你收集整理的leetcode_Jump Game II的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。