您的位置:首页 > 其它

LeetCode Jump Game II

2016-07-25 12:22 387 查看
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.)

这道题可以用Dynamic Programming做,DP可以从前面往后面推,可以从后面往前面推,刚开始我的想法是从后面往前面推

DP[i] 有可能从DP[i-1],DP[i-2],DP[i-3]……. 推过来,所以这道题的最好方式是从前面往后面推 DP[i]代表第i个位置的所需要的最短的的跳步

所以DP的代码是

int[] nums = new int[];
for(int i=0;i<nums.length;i++){
for(int j=i+1;j+nums[i]<nums.length;j++){
dp[j] = Math.min(dp[i]+1,dp[j])
}
}
//这个方法的时间复杂度是O(n*n)


还有一种方法就是O(n)的时间复杂度,遍历整个数组,设置2个指针

i_max 代表当前位置能走到的最大步数

pre_max 代表上一个index能走道的最大位置

向前遍历数组,如果i是大于pre_max的,就更新pre_max

最关键的问题是什么时候步数加一,一般的情况是i>pre_max的时候就可以更新一步了
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode