c++ - 理解算法的复杂性

标签 c++ algorithm time-complexity big-o asymptotic-complexity

我正在看一些编码面试的在线算法解决方案,我不明白为什么这个算法声称是 O(n^3)。

Caveat: I understand that big-Oh notation is abused in industry, and when I refer to O(n), I'm using that notation to mean the upper bound of an algorithms runtime as is common outside of academia in most places.

寻找最长的回文子串。一个简单的解决方案可能是:

bool isPalindrome(std::string s) {
  if (s.length() <= 1) {
    return true;
  }

  if (s[0] == s[s.length() - 1]) {
    return isPalindrome(s.substr(1, s.length() - 2));
  } else {
    return false;
  }
}

std::string longestPalindrome(std::string s) {
  std::string max_pal = "";
  for (size_t i = 0; i < s.length(); ++i) {
    for (size_t len = 1; len <= s.length() - i; ++len) {
      std::string sub = s.substr(i,len);
      if (isPalindrome(sub)) {
        if (max_pal.size() < sub.size()) max_pal = sub;
      }
    }
  }
  return max_pal;
}

这个算法不是O(n^2)吗?很简单,生成所有子串需要O(n^2)的时间,判断是否回文需要O(n)的时间。其中 n 是初始字符串中的字符数。

最佳答案

Isn't this algorithm O(n^2)? Very simply, it takes O(n^2) time to generate all substrings, and O(n) time to determine if it's a palindrome.

您所描述的恰好是 O(n^3),因为对于每个子字符串,您正在执行一个成本为 O(n) 的操作,因此总数操作是 O(n^2 * C*n),也就是 O(n^3)


但是,描述的代码其实是O(n^4)isPalindrome()O(n^2 ):

  • 您正在创建 O(n) 个子字符串,大小为:1 + 3 + 5 + ... + n-2,即 O( n^2) 总时间。
  • longestPalindrome() 中执行此 O(n^2) 次总计为 O(n^4)

(假设 O(n) substr() 复杂性。它没有定义 - 但 it's usually the case )

关于c++ - 理解算法的复杂性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47583739/

相关文章:

algorithm - 优化有向无环图中的连接查询

vb.net - 在VB中寻找模拟退火实现

c++ - 在 C++ 中逐行读取 const 数据

c++ - RTKlib(C 库)与 QT(C++ 代码)

c++ - 如何减少录音程序中的CPU消耗(c++)

C++ 快速排序算法

c++ - ARM和Intel发生奇怪的崩溃

java - 为什么第二个代码比第一个更有效?

java - Java中Stack和Queue实现不同的原因?

algorithm - 计算递归算法的时间复杂度