【问题标题】:Getting the time complexity获取时间复杂度
【发布时间】:2021-07-02 10:15:24
【问题描述】:

我写了这个算法。你能帮我计算“时间复杂度”吗? 我没有嵌套函数,但在 map 中有 .includes。

function prime(num) {
  for (var i = 2; i < num; i++) if (num % i === 0) return false;
  return num > 1;
}

const function = (dataA, dataB) => {
  let temp = {};
  let tempArray = [];
  dataB.forEach(function (x) {
    temp[x] = (temp[x] || 0) + 1;
  });
  dataA.map(item => {
    if (dataB.includes(item) && !prime(temp[item])) {
      tempArray.push(item);
    } else if (!dataB.includes(item)) {
      tempArray.push(item);
    }
  });
  return tempArray;
};

console.log('Input A:', A);
console.log('Input B:', B);
console.log('Output:', function(A, B));

【问题讨论】:

    标签: javascript algorithm time-complexity


    【解决方案1】:

    一些观察:

    • B.includes 的时间复杂度为 O(B.length)

    • isPrime 的时间复杂度为 O(num)。由于参数是 B 中某个值的频率,它受 B 大小的限制,因此它的最坏情况为 O(B.length),因为只有在调用 B.includes 时才会调用 isPrime,因此,它与整体时间复杂度无关。

    • 由于 B.includes 的调用次数与 A 中的值一样多,因此总体时间复杂度为 O(A.length * B.length)

    可以通过将B.includes(item) 替换为count[item] 来降低复杂性,然后isPrime 变为确定性。如果 isPrime 使用 memoization 进行扩展,所有 isPrime 调用的总成本为 O(A.length + B.length),那么这也是整体时间复杂度。

    这不能进一步减少,因为即使没有调用 isPrime,对两个输入数组的迭代也是必要的,并且已经代表了时间复杂度。

    【讨论】:

      【解决方案2】:

      isPrime 函数的最坏情况时间复杂度为 O(n)。

      forEach 函数是一个单独的 O(n) 函数。

      map 函数评估 dataA 中的每个项目并在 includesisPrime 函数中的每一个中执行 O(n)。

      因此,总时间复杂度为 O(n^2)。

      【讨论】:

        猜你喜欢
        • 2016-02-13
        • 2012-08-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-09-12
        • 2018-08-02
        相关资源
        最近更新 更多