本文主要是介绍let 45 Jump Game II,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
主题思想: 这是一道贪心算法, 要尽可能地跳的远,首先 明确什么时候更新步数, 根据当前i 能知道从i 能走到的最大步数 ith-long,在没走到ith-long达到的最大步数之前,记录中间步骤所能更新的最大值,当i达到ith-long 是更新下一步最大值为中间的最大值,并更新步数。
class Solution {public int jump(int[] nums) {if(nums==null||nums.length<2) return 0;int n=nums.length;int step=0,longestDistance=0,nextLongestDistance=0;// the nums[n-1] can be reached by [n-1] ....0 so, i from 0 to n-2for(int i=0;i<n-1;i++){//nextLongestDistance 是i到longestDistance 所能走到的最大步数nextLongestDistance=Math.max(nextLongestDistance,i+nums[i]);//当i达到最大步数时,更新step,if(i==longestDistance){longestDistance=nextLongestDistance;step++;}}return step;}
}
这篇关于let 45 Jump Game II的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!