一个面试题。题目: 计算五分钟内的平均值。 一个函数接收数值,一次接收一个。不确定下一个数值来的时间。你需要做的就是设计一个函数 mean(),计算从现在开始到五分钟前,接收到的所有数值的平均值
代码
#include <iostream>
#include <unordered_map>
#include <unordered_set>
#include <stack>
#include <string>
#include <vector>
#include <queue>
#include <map>
#include <algorithm>
#include <chrono>
#include <thread>
using namespace std;
using namespace std::chrono;
long long currentTime() {
return duration_cast<microseconds>(steady_clock::now().time_since_epoch()).count();
}
class MeanLimiter {
private:
vector<long long> data;
vector<long long> prefixSum;
int sz = 0;
long long last = -1;
void enlargeIfNeed() {
if (sz >= data.size()) {
int new_sz = data.size() * 2 + 4;
if (data.size() > 1000) {
new_sz = data.size() + 1000;
}
data.resize(new_sz);
prefixSum.resize(new_sz);
cout << "enlarge " << new_sz << "\n";
}
}
public:
void push(int value) {
auto t = currentTime();
last = t;
long long pre = 0;
enlargeIfNeed();
data[sz] = t;
if (sz > 0) {
pre = prefixSum[sz - 1];
}
prefixSum[sz] = pre + value;
++sz;
}
void moveIfNeed(int index) {
if (index * 2 >= sz + 4 || index > 1000) {
cout << "\ttry move\t" << index << "\t" << sz - index << "\n";
long long pre = prefixSum[index - 1];
for (int x = 0; x + index < sz; x++) {
data[x] = data[x + index];
prefixSum[x] = prefixSum[x + index] - pre;
}
sz -= index;
}
}
double mean() {
if (-1 == last) {
return -1;
}
long long start = last - 3e6;
// 二分查找第一个大于等于的下标
int index = lower_bound(data.begin(), data.begin() + sz, start) - data.begin();
int count = sz - index;
long long sum = prefixSum[sz - 1];
if (index > 0) {
sum -= prefixSum[index - 1];
moveIfNeed(index);
cout << "\t index: " << index << "\t";
}
return (sum * 1.0) / count;
}
};
int main() {
MeanLimiter mean;
for (int i = 0; i < 10; i++) {
int v = random() % 5 + 1;
mean.push(v);
cout << i << "\t" << v << "\t" << mean.mean() << endl;
int st = random() % 3000000;
this_thread::sleep_for(microseconds(st));
}
}
#输出
c++ 计算五分钟内的平均值
c++ 计算五分钟内的平均值
c++ 计算五分钟内的平均值
c++ 计算五分钟内的平均值
c++ 计算五分钟内的平均值
c++ 计算五分钟内的平均值
c++ 计算五分钟内的平均值
c++ 计算五分钟内的平均值
c++ 计算五分钟内的平均值
c++ 计算五分钟内的平均值