简体   繁体   中英

Time limit exceeded even after doing an upper_bound on the array

Language used: C++14.

I am given 2 sorted arrays A and B. Now, for each element in A i have to find a greater element in B if it is possible and note that once i have found an element in B for a particular element in A, i can only search ahead of that index in B. I am doing something like this:

int j=0;
for(i=0;i < A.size();i++)
{
    int index = upper_bound(B.begin()+j,B.end(),A[i]) - B.begin();
    if(index>=B.size()){
        break;
    }
    else{
        cout<<"For A[]"<<A[i]<<" element "<<B[index]<<" is greater "<<"\n";
        j = index + 1;
    }
}

Even while i am doing a binary search using upper_bound still the program gives Time limit exceeded for large array ( say of size 1000000 ).

I cannot figure out the reason why?

PS: i know that this can be done using 2 pointers in linear time, however i wanted to know why my solution failed . I am a new comer, so please help me out.

First of all make sure that the first iterator in your upper_bound is <= second iterator as it may happen that for some number the last element in array B is greater than it, so now if you do j = index + 1, it will be equal to B.end(), now searching for any greater element would always return some integer greater than length of B which is not possible.

Secondly, for your question:

int index = upper_bound(B.begin()+j,B.end(),A[i]) - B.begin();

This line is moving the first iterator by 'j' steps first and not in constant time and then applying upper_bound would result in a time complexity of o(n*n*log(n))

n: for iterating over A

n: for moving by 'j' steps which in worst case can be n

log(n): for upper_bound

which is causing Time Limit for larger arrays.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM