【问题标题】:How to find the product of all the possible subarrays in an array in linear time?如何在线性时间内找到数组中所有可能子数组的乘积?
【发布时间】:2020-04-05 19:26:59
【问题描述】:

假设我有一个数组 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) 复杂度中找到?谢谢!

【问题讨论】:

    标签: arrays dynamic-programming number-theory


    【解决方案1】:

    不,这是不可能的,因为结果的大小是二次的(特别是 n(n+1)/2)。只写结果的每一项就已经花费了二次时间,无论计算起来多么容易。

    【讨论】:

      猜你喜欢
      • 2020-07-17
      • 1970-01-01
      • 2016-01-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-05
      • 1970-01-01
      • 2011-05-31
      相关资源
      最近更新 更多