Jump Game II
My naive running time solution:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | class Solution { public : int jump( int A[], int n) { if (1 == n) return 0; int maxL = (1<<31) - 1; int *jumps = new int [n]; jumps[0] = 0; for ( int i = 1; i < 1; ++i) jumps[i] = maxL; for ( int i = 1; i < n; ++i) for ( int j = 0; j < i; ++j) //offer information for i if (A[j] >= (i-j) && jumps[j]+1 < jumps[i]) jumps[i] = jumps[j] + 1; int result = jumps[n-1]; delete []jumps; if (result != maxL) return result; return -1; } }; |
What we need to do is just optimizing the code. In fact, we only need to optimize one place:
1 2 3 | for ( int j = 0; j < i; ++j) //offer information for i if (A[j] >= (i-j) && jumps[j]+1 < jumps[i]) jumps[i] = jumps[j] + 1; |
Here, we use to store the minimum jumps to reach position .
In fact, once we get the if statement, we can break. Because the remaining results must be greater than or equal to the current results of .
Let's give a proof.
Let's suppose existing , where , such that , i.e. . Without losing the generality, we can assume is the first element satisfy these conditions, which means the element , where , satisfying .
- We can use induction.
- Let's consider the last position, , to jump to , which means .
- If : because the array can jump to from , and , it also means we can jump to from .
So- If : that means , i.e. .
- If : because is the first element satisfy . So .
All these situations are contradictions. So, we finish our proof.
Thus we can optimize our code like:
1 2 3 4 5 | for ( int j = 0; j < i; ++j) //offer information for i if (A[j] >= (i-j) && jumps[j]+1 < jumps[i]){ jumps[i] = jumps[j] + 1; break ; } |
One more slight tricky ignoring Time Limit Exceed, we can put the initialization into our second for loop. The final code is:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | class Solution { public : int jump( int A[], int n) { if (1 == n) return 0; int maxL = (1<<31) - 1; int *jumps = new int [n]; jumps[0] = 0; for ( int i = 1; i < n; ++i){ jumps[i] = maxL; for ( int j = 0; j < i; ++j) //offer information for i if (A[j] >= (i-j) && jumps[j]+1 < jumps[i]){ jumps[i] = jumps[j] + 1; break ; } } int result = jumps[n-1]; delete []jumps; if (result != maxL) return result; return -1; } }; |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· winform 绘制太阳,地球,月球 运作规律
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 上周热点回顾(3.3-3.9)