- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
我必须设计一个订单簿 数据结构,允许我查询已插入但尚未删除的订单的最高价格。插入和删除操作在文件中预先给出,其中每个操作看起来像以下两个操作之一:
其中 ID 是一个顺序的整数标识符,时间戳始终按递增顺序排列,每个 ID 恰好出现两次:一次在插入操作中,一次在删除操作中,按此顺序。
从这个操作列表中,我需要输出最高价格的时间加权平均值。
例如,假设我们有以下输入:
我们可以说在
10 I 1 10
20 I 2 13
22 I 3 13
24 E 2
25 E 3
40 E 1ith
之后操作,最大是 10, 13, 13, 13, 10
时间加权平均值是 10*(20-10) + 13*(22-20) + 13*(24-22)+13*(25-24)+10*(40-25) = 10.5
因为10
是时间戳 [10-20]
之间的最高价格和 [25,40]
其余 13 人。
我正在考虑使用 unordered_map<ID,price>
和一个 multiset<price>
支持:
O(log(n))
O(log(n))
O(1)
这是我想出的一个例子:
struct order {
int timestamp, id;
char type;
double price;
};
unordered_map<uint, order> M;
multiset<double> maxPrices;
double totaltime = 0;
double avg = 0;
double lastTS = 0;
double getHighest() {
return !maxPrices.empty() ? *maxPrices.rbegin()
: std::numeric_limits<double>::quiet_NaN();
}
void update(const uint timestamp) {
const double timeLeg = timestamp - lastTS;
totaltime += timeLeg;
avg += timeLeg * getHighest();
lastTS = timestamp;
}
void insertOrder(const order& ord) {
if (!maxPrices.empty()) {
if (ord.price >= getHighest()) {
// we have a new maxPrice
update(ord.timestamp);
}
} else // if there are not orders this is the mex for sure
lastTS = ord.timestamp;
M[ord.id] = ord;
maxPrices.insert(ord.price);
}
void deleteOrder(
const uint timestamp,
const uint id_ord) { // id_ord is assumed to exists in both M and maxPrices
order ord = M[id_ord];
if (ord.price >= getHighest()) {
update(timestamp);
}
auto it = maxPrices.find(ord.price);
maxPrices.erase(it);
M.erase(id_ord);
}
这种方法的复杂度为 nlogn
其中 n
是活跃订单数。
有没有更快的渐近和/或更优雅的方法来解决这个问题?
最佳答案
我建议您采用数据库 方法。
将所有记录放入 std::vector
.
创建索引表,std::map</* key type */, size_t>
,它将包含一个键值和 vector 中记录的索引。如果您希望键按降序排序,还需要提供一个比较仿函数。
此策略允许您创建许多索引表而无需重新排序所有数据。该 map 将为您的 key 提供良好的搜索时间。您还可以遍历映射以按顺序列出所有键。
注意:对于现代计算机,您可能需要大量数据才能在二分搜索( map )和线性搜索( vector )之间提供显着的时间改进。
关于c++ - 数据结构 : insert(id, 值)、delete(id) 和 getMax(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46118715/
这个问题在这里已经有了答案: Inline functions vs Preprocessor macros (14 个答案) 关闭 8 年前。 如果我的程序需要一个简单的函数,假设要确定两个数字的
我是 Java 菜鸟,我遇到了一个问题。 所以作业是这样的 There is one method required: getMax, which takes two integer variable
在应用“最佳实践”的同时优化以下代码以使其更高效的最佳方法是什么。这只是一个简单的学校项目,它有效,我已经测试过了。但我只是觉得有一种更好、更有效的方法来编写这个方法。你怎么看? 我有一个数组预先填充
本文整理了Java中org.eclipse.scada.chart.YAxis.getMax()方法的一些代码示例,展示了YAxis.getMax()的具体用法。这些代码示例主要来源于Github/S
我必须设计一个订单簿 数据结构,允许我查询已插入但尚未删除的订单的最高价格。插入和删除操作在文件中预先给出,其中每个操作看起来像以下两个操作之一: TIMESTAMP insert ID PRICE
我是一名优秀的程序员,十分优秀!