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

时间:2020-07-27 20:38:25

标签: 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重复相同的长度。

1 个答案:

答案 0 :(得分:1)

它是:

  • 严格来说:O(2n),在最坏的情况下,您迭代输入大小的两倍;
  • 渐近语言O(n),因为忽略了恒定因子is