gpt4 book ai didi

c++ - 如何计算比 O(n^2) 更好的最小平均子数组?

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:42:19 26 4
gpt4 key购买 nike

<分区>

我编写了以下代码来计算平均值最小的子数组(最少两个元素)的最小起始索引。

但是,无法想出如何让它更快的方法,即 O(n) 或 O(n log n) 的方法。我想不出有什么方法可以在不达到 O(n^2) 的情况下“访问”所有可能的子数组:

#include <iostream>
#include <vector>
#include <limits>

using namespace std;

int solution(vector<int> &A) {
float previousAvg = 0.0;
float minAvg = numeric_limits<float>::max();
int minStartIx = numeric_limits<int>::max();
for (size_t i = 0; i < A.size(); ++i) {
for (size_t j = i + 1; j < A.size(); ++j) {
if (j == i + 1) {
previousAvg = (A[i] + A[j]) / 2.0;
cout << "avg(from=" << i << ", to=" << j << ") = " << previousAvg << endl;
} else {
previousAvg = (previousAvg * (j - i) + A[j]) / (j - i + 1);
cout << "avg(from=" << i << ", to=" << j << ") = " << previousAvg << endl;
}
if (previousAvg < minAvg) {
minAvg = previousAvg;
minStartIx = i;
}
}
}
return minStartIx;
}

int main() {
vector<int> A = {4, 2, 2, 5, 1, 5, 8};
cout << solution(A) << " must equal to 1" << endl;
return 0;
}

并通过日志记录产生正确的输出:

avg(from=0, to=1) = 3
avg(from=0, to=2) = 2.66667
avg(from=0, to=3) = 3.25
avg(from=0, to=4) = 2.8
avg(from=0, to=5) = 3.16667
avg(from=0, to=6) = 3.85714
avg(from=1, to=2) = 2
avg(from=1, to=3) = 3
avg(from=1, to=4) = 2.5
avg(from=1, to=5) = 3
avg(from=1, to=6) = 3.83333
avg(from=2, to=3) = 3.5
avg(from=2, to=4) = 2.66667
avg(from=2, to=5) = 3.25
avg(from=2, to=6) = 4.2
avg(from=3, to=4) = 3
avg(from=3, to=5) = 3.66667
avg(from=3, to=6) = 4.75
avg(from=4, to=5) = 3
avg(from=4, to=6) = 4.66667
avg(from=5, to=6) = 6.5
1 must equal to 1

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com