arrays - 如何在线性时间内找到数组中所有可能子数组的乘积?
问题描述
假设我有一个数组 A[4] = {5,6,2,4}
子数组是:{{5}, {6}, {2}, {4}, {5, 6}, {6, 2}, {2, 4}, {5, 6, 2}, { 6, 2, 4}, {5, 6, 2, 4}}
我需要包含每个子数组的乘积的数组作为输出,即 {5, 6, 2, 4, 30, 12, 8, 60, 48, 240}
这是我的 O(n^2) 方法:
const int a = 4;
const int b = 10; //n(n+1)/2
int arr[a] = {5, 6, 2, 4};
int ans[b] = {0};
int x = 0;
for(int i = 0; i < n; i++) {
prod = 1;
for(int j = i; j < n; j++) {
prod *= arr[j];
ans[x++] = prod;
}
}
//ans is the o/p array
我想知道这是否可以在 O(n) 复杂度中找到?谢谢!
解决方案
不,这是不可能的,因为结果的大小是二次的(特别是 n(n+1)/2)。仅仅写出结果的每一个条目就已经花费了二次时间,不管计算它有多容易。
推荐阅读
- google-bigquery - 使用 Cloud Deployment Manager 创建 BigQuery 物化视图
- visual-studio-code - 在 Visual Studio Code 中设置全局环境变量
- powerbi - Power BI 桌面中的多列排序
- c++ - __USE_BSD 标志在哪里定义?
- javascript - 获取 ngx-owl-carousel 的产品构建错误
- xaml - 如何制作可更改的 Xamarin.Form Xaml 页面?
- python - 尝试使用条件公式在 python pandas 中构建迭代列
- c - C中浮点数据类型的结构(二进制格式)是什么?
- typescript - 错误 TS2339:使用 Array 与 ReadonlyArray 有什么区别?
- haskell - 从 State Monad 获取结果和状态,而不仅仅是状态