algorithm - 这个算法的时间复杂度是多少?

标签 algorithm complexity-theory big-o time-complexity

假设我们有一个数组w,其中包含n 个整数。通过以下定义和以下伪代码,请告诉我算法 w.r.t. 的时间复杂度是多少。 n:

idx[i] = max(j) : 1 <= j < i and w[j] < w[i]

alg:
Data: w : array of integers - idx: a pointer to maximum index with the less value.
Date: w is 1based

idx[1] = -1
for i=: 2 to n do
  j=i-1
  while w[j] > w[i] and j <> -1
  {
    j = idx[j]
  }
  idx[i] =j
end

最佳答案

这里有 2 个循环 -

  1. 第一个循环 for loop 运行 n 次。因此它的 O(n)。
  2. 第二个循环 while loop 每次从 (i-1) + (i-2) + (i-3) + .... + (i-n) 运行>。它运行 (n-1) 次。所以 O(n)。

合并为 O(n^2) 算法。其他操作要么是常数时间要么是 O(n) 时间,因此被忽略。

关于algorithm - 这个算法的时间复杂度是多少?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15041054/

相关文章:

c - 为什么 counter = counter/2;有 O(log(n))?

python - 使用数字加密文本

algorithm - 动态规划——修改自下而上的切杆算法

algorithm - 如何构建堆的时间复杂度为 O(n)?

algorithm - 如何按大小对数字进行分组

python - Python中bin()的时间复杂度

java - 比较循环中的元素。如何最好地避免与自己比较?

algorithm - 大O还是大欧米茄?

algorithm - 如何使用签名数据、签名和签名者 ECDSA 公钥验证 ECDSA 签名?

algorithm - 使用按位运算求给定数字的平方根