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的代码是
还有一种方法就是O(n)的时间复杂度,遍历整个数组,设置2个指针
i_max 代表当前位置能走到的最大步数
pre_max 代表上一个index能走道的最大位置
向前遍历数组,如果i是大于pre_max的,就更新pre_max
最关键的问题是什么时候步数加一,一般的情况是i>pre_max的时候就可以更新一步了
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 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- leetcode----Longest Substring Without Repeating Characters
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- leetcode_linearList
- leetcode_linearList02
- 021-Merge Two Sorted Lists(合并两个排好序的单链表);leetcode
- LeetCode[Day 1] Two Sum 题解
- LeetCode[Day 2] Median of Two Sorted Arrays 题解
- LeetCode[Day 3] Longest Substring Without... 题解
- LeetCode [Day 4] Add Two Numbers 题解