LintCode "Subarray Sum Closest"
2015-10-12 02:32
302 查看
O(nlgn) - my first thought is, keep maintaining a balanced binary search tree, and then use "Binary Search Tree Closest" one to solve it. But unfortunately there's no on-hand stl class for it. The closest one is multiset<T>.
However, we don't have to use binary search tree. Since we are looking for closest partial sum - we can sort it, then check neighbor 2.
However, we don't have to use binary search tree. Since we are looking for closest partial sum - we can sort it, then check neighbor 2.
class Solution { public: /** * @param nums: A list of integers * @return: A list of integers includes the index of the first number * and the index of the last number */ vector<int> subarraySumClosest(vector<int> nums) { if (nums.empty()) { return {}; } const int n = nums.size(); vector<pair<int, int>> psum(n + 1); // Get and Sort the partial sum. a little greedy for (int i = 0; i < n; ++i) { psum[i + 1].first = psum[i].first + nums[i]; psum[i + 1].second = i + 1; } sort(psum.begin(), psum.end()); int d = INT_MAX; int ri = 1; for (int i = 1; i < n + 1; ++i) { int curr = abs(psum[i].first - psum[i - 1].first); if (d > curr) { d = curr; ri = i; } } int l = min(psum[ri - 1].second, psum[ri].second); int r = -1 + max(psum[ri - 1].second, psum[ri].second); return {l, r}; } };
相关文章推荐
- Sliding Window Maximum
- Ember.js 入门指南——自定义包裹组件的HTML标签
- Local & Global
- 分清定义性声明和引用性声明
- 解决方案:An error was encountered while running(Domain=FBSOpenApplicationErrorDomain, Code=4)
- MySQL
- Struts 2中的constant详解
- LintCode Number of Airplanes in the Sky(Java)
- JAVA初学者复习笔记整理(1)
- Eclipse使用Ruby
- 【linux】自己常用命令总结
- *LeetCode-Candy
- 学习笔记
- CentOS7安装MySQL冲突和问题解决小结
- java实验报告(实验二)
- Part 36 to 39 Talking about Delegates in c#
- [Javascript] Using JSHint for Linting with Gulp
- [ReactNative入门到精通]React Native 第一个程序 Hello Word
- 简单的JSP分页显示
- 高项10月10日作业