[LeetCode] Jump Game II 解题报告
来源:互联网 发布:ug10.0加工编程铣平面 编辑:程序博客网 时间:2024/05/16 15:17
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 =
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.)» Solve this problem
[解题思路]
二指针问题,最大覆盖区间。
从左往右扫描,维护一个覆盖区间,每扫过一个元素,就重新计算覆盖区间的边界。比如,开始时区间[start, end], 遍历A数组的过程中,不断计算A[i]+i最大值(即从i坐标开始最大的覆盖坐标),并设置这个最大覆盖坐标为新的end边界。而新的start边界则为原end+1。不断循环,直到end> n.
[Code]
1: int jump(int A[], int n) {
2: // Start typing your C/C++ solution below
3: // DO NOT write int main() function
4: int start = 0;
5: int end = 0;
6: int count =0;
7: if(n == 1) return 0;
8: while(end < n)
9: {
10: int max = 0;
11: count++;
12: for(int i =start; i<= end ; i++ )
13: {
14: if(A[i]+i >= n-1)
15: {
16: return count;
17: }
18: if(A[i]+ i > max)
19: max = A[i]+i;
20: }
21: start = end+1;
22: end = max;
23: }
24: }
[注意]
Line7,当n=1的时候,需要特殊处理一下。
0 0
- Leetcode Jump Game II 解题报告
- 【LeetCode】Jump Game II 解题报告
- [leetcode] 45. Jump Game II 解题报告
- [LeetCode] Jump Game II 解题报告
- leetcode解题报告:45. Jump Game II
- [Leetcode] 45. Jump Game II 解题报告
- Leetcode #45. Jump Game II 跳跃游戏2 解题报告
- Leetcode Jump Game 解题报告
- 【LeetCode】Jump Game 解题报告
- [LeetCode] Jump Game 解题报告
- [leetcode] 55. Jump Game 解题报告
- LeetCode解题报告 55. Jump Game [medium]
- [Leetcode] 55. Jump Game 解题报告
- LeetCode 55. Jump Game 解题报告
- leetcode解题方案--045-- Jump Game II
- LeetCode: Jump Game II
- LeetCode Jump Game II
- LeetCode: Jump Game II
- [LeetCode] Insert Interval 解题报告
- [LeetCode] Integer to Roman 解题报告
- [LeetCode] Interleaving String 解题报告
- 采用dlopen、dlsym、dlclose加载动态链接库【总结】
- [LeetCode] Jump Game 解题报告
- [LeetCode] Jump Game II 解题报告
- [LeetCode] Largest Rectangle in Histogram 解题报告
- [Leetcode] Length of Last Word 解题报告
- [LeetCode] Letter Combinations of a Phone Number 解题报告
- [LeetCode] Longest Common Prefix 解题报告
- [LeetCode] Longest Palindromic Substring 解题报告
- Android网络缓存的实现思路
- [LeetCode] Longest Substring Without Repeating Characters 解题报告
- [LeetCode] Maximum Depth of Binary Tree