首页 > 代码库 > LeetCode Jump Game II
LeetCode Jump Game II
class Solution {private: vector<long> sum; vector<long> step; set<int> can;public: int jump(int A[], int n) { step.clear(), sum.clear(), can.clear(); step.resize(n, INT_MAX), sum.resize(n, 0); int jmp = A[0]; can.insert(n - 1); step[n - 1] = 0; for (int i = n - 2; i>= 0; i--) { jmp = A[i]; if (i + jmp >= n - 1) { sum[i] = sum[i + 1] + 1; can.insert(i); continue; } int region = sum[i + 1] - sum[i + jmp + 1]; if (region > 0) { sum[i] = sum[i + 1] + 1; can.insert(i); } else { sum[i] = sum[i + 1]; } } if (can.size() > 1 && (jmp >= n-1 || sum[0] - sum[jmp] > 0)) { can.insert(0); } int cur_jmp_to; int pre_jmp_to = n-1 + A[n - 1]; for (int i = n - 2; i >= 0; i--) { cur_jmp_to = i + A[i]; int min_step = INT_MAX; if (cur_jmp_to >= pre_jmp_to) { min_step = step[i + 1] - 1; if (min_step < 0) min_step = 0; for (int j = pre_jmp_to; j < n && j <= cur_jmp_to; j++) { if (step[j] < min_step) min_step = step[j]; } } else if (A[i] > 0){ set<int>::iterator lower = can.lower_bound(i+1); set<int>::iterator upper = can.upper_bound(cur_jmp_to); while (lower != upper) { if (step[*lower] < min_step) min_step = step[*lower]; lower++; } } step[i] = min_step == INT_MAX ? INT_MAX : min_step + 1; pre_jmp_to = cur_jmp_to; } return step[0]; }};
状态不佳,错了好多,100ms+,感觉好吃力。想起以前高中做数学题那会儿,看叼的人两三下把题目做出来了,自己写满一页还没算出来,真是tmd的不是滋味,不找规律,强来就是这样的结果,我tmd已经看穿了。
时间O(n),空间O(1)算法参考:http://www.cnblogs.com/zhuli19901106/p/3568216.html
// cloned from zhuliclass Solution {public: int jump(int A[], int n) { if (A == nullptr || n <= 0) { return -1; } else if (n == 1) { return 0; } int last_pos, this_pos; int i; int result; last_pos = 0; this_pos = 0; result = 0; for (i = 0; this_pos < n - 1; ++i) { if (i > this_pos) { return -1; } if (i + A[i] > this_pos) { if (i > last_pos) { last_pos = this_pos; ++result; } this_pos = i + A[i]; } } return result + 1; }};
时间上快了一倍50ms+
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。