博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LintCode "Subarray Sum Closest"
阅读量:5273 次
发布时间:2019-06-14

本文共 1494 字,大约阅读时间需要 4 分钟。

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.

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
subarraySumClosest(vector
nums) { if (nums.empty()) { return {}; } const int n = nums.size(); vector
> 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}; }};

转载于:https://www.cnblogs.com/tonix/p/4870588.html

你可能感兴趣的文章
线程池的概念
查看>>
Oracle_Statspack性能诊断工具
查看>>
转获取sql维护的表关系
查看>>
Java 序列化
查看>>
Java 时间处理实例
查看>>
Java 多线程编程
查看>>
Java 数组实例
查看>>
mysql启动过程
查看>>
2017前端面试题总结
查看>>
Http GetPost网络请求
查看>>
SWIFT国际资金清算系统
查看>>
Sping注解:注解和含义
查看>>
站立会议第四天
查看>>
如何快速掌握一门技术
查看>>
利用AMPScript获取Uber用户数据的访问权限
查看>>
vagrant 同时设置多个同步目录
查看>>
python接口自动化28-requests-html爬虫框架
查看>>
生成随机数的模板
查看>>
Mysql 数据库操作
查看>>
转:linux终端常用快捷键
查看>>