Блог пользователя daihan

Автор daihan, 5 лет назад, По-английски

In a problem i needed just unique elements , so i used set but got time limit exceeded but Later used vector unique + resize() and got AC . I don't know how is this possible , because both code has time complexity of O(nlog(n));

    set<int> st;
    
    for(int i=0;i<n;i++)    
         st.insert(i); // log(n)

This code time complexity: O(nlog(n+container size) )

===================================================================================

       vector<int> vct;       
       for(int i=0;i<n;i++)
         vct.push_back(i);
       
       sort(vct.begin(),vct.end());  // nlogn
       auto it=unique(vct.begin(),vct.end()) ;  // n
       vct.resize(it - vct.begin() ); // n

This code time complexity: O(nlog(n) + n + n) which is approximately equals to O(nlog(n) + n) . Am i wrong in calculating Time Complexity? nlogn for sorting and one n for unique function call , another n for resize() method call

So , O(nlog(n+container size) ) is almost equals to O(nlog(n) + n) but why they depicts different scinario ?

  • Проголосовать: нравится
  • -7
  • Проголосовать: не нравится

»
5 лет назад, # |
  Проголосовать: нравится 0 Проголосовать: не нравится

Constant factor.

»
5 лет назад, # |
Rev. 3   Проголосовать: нравится 0 Проголосовать: не нравится

set has C1 * n * log N

vector has C2 * n * log N

С1 is much bigger than С2

»
5 лет назад, # |
  Проголосовать: нравится +3 Проголосовать: не нравится

O(n * log n) is asymptotic time complexity notation not the exact time complexity for both operations as you told. In asymptotic TC notation we just compute the proportional term of input size and ignore the constant factors which does not change with input size. See This link for details.