c++ - 带内部while循环的while循环:O(n)或O(n ^ 2)?

标签 c++ algorithm big-o

#include <unordered_map>
using namespace std;

        int lengthOfLongestSubstring(string s) {
            
            unordered_map<char, int> ht;
            int max = 0;
            
            int i = 0; int j = 0; 
            while (i < s.size() && j < s.size()) {
                
                if (ht.find(s.at(j)) == ht.end()) {
                    ht.insert( {s.at(j), j} );
                    max = (j - i + 1 > max) ? j - i + 1 : max;
                    j++;
                }
                else {
                    int len = ht.at(s.at(j)) + 1;
                    while(i < len) {
                        ht.erase(s.at(i));
                        i++;
                    }
                    
                }
                
            }
            
            return max;
        }
时间复杂度是O(n)还是O(n^2)?为什么?
我的直觉是它是O(n),i和j遍历相同的长度。

最佳答案

它的:

  • 严格来说:O(2n),在最坏的情况下,您迭代输入大小的两倍;
  • 用渐近语言讲:O(n),因为忽略常量因子is
  • 关于c++ - 带内部while循环的while循环:O(n)或O(n ^ 2)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63123206/

    相关文章:

    c++ - GCC 相当于 MS/bigobj

    c++ - openCV c++ : Problems working with CvBoost (Adaboost classifer)

    c++ - 如何在基本 block 中插入LLVM StoreInst

    c++ - 为什么 `for` 语句范围的特殊规则?

    algorithm - 排序算法的上下界

    algorithm - 计算 n 为 nlog(n) 和 n!当时间为 1 秒时。 (算法需要 f(n) 微秒)

    arrays - 数组搜索的伪代码

    algorithm - 有没有办法从文件中存储 gzip 的字典?

    python - 用 n 表示具有整数 A i,j := sin(z i, j) 的 nxn 数组,其中 zi, j 是 (0,2pi] 中均匀分布的随机数

    algorithm - 以下方法在 Big-O 表示法方面的时间复杂度是多少?