日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

leetcode_Jump Game II

發布時間:2025/5/22 编程问答 36 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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的全部內容,希望文章能夠幫你解決所遇到的問題。

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