首页 > 代码库 > LeetCode "Jump Game II"
LeetCode "Jump Game II"
Greedy, Greedy, Greedy.. It is all about maximum interval update.
One trick is, we start looping over each element from the one nearest to end to farthest one - because the nearer the index is, more hopeful it could finish earlier. With this optimization, I got it passed with only 24ms.
class Solution {public: int jump(int A[], int n) { if (n <= 1) return 0; int last = 0, inx = 0; int cnt = 0; while (inx < n) { int newMaxInx = 0; int tmp_i = inx + 1; while (tmp_i--) { if (tmp_i < last) break; newMaxInx = std::max(newMaxInx, A[tmp_i] + tmp_i); if (newMaxInx >= n - 1) return cnt + 1; } last = inx; inx = newMaxInx; cnt++; } return cnt; }};
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。