简体   繁体   中英

Improving Time Complexity

I would appreciate some feedback with regards to Big-O (time-complexity) of loops, or, ways to improve it.

Let's take the following:

var pairs = 0;
HashSet<int> hs = new HashSet<int>(n);
for (var i = 0; i < ar.Length; i++)
{
    if(!hs.Contains(ar[i]))
        hs.Add(ar[i]);
    else
    {
        pairs++;
        hs.Remove(ar[i]);
    }
}

return pairs;

From what I can determine, the worst-case time-complexity of the above is: O(n), because of the loop.

Are the any way of improving this, to bring the time-complexity as close to O(1) as possible?

PS: I'm pretty sure that the the above will never be O(1).

Thank you

If you need to count pairs like this across n items, by definition you cannot do better than O( n ) because you need to look at each item. Just iterating through the items is O( n ) and any item may be part of a pair so you need to iterate through them all.

That is, unless you are dealing with some special case in which it is possible to figure out how many pairs there has to be by the pigeonhole principle , if the items may have only m unique values and m < n . Say you have 5 items and each item can only be "A" or "B" then you know there are going to two pairs without even looking at the items; the time complexity of coming up with 2 is O(1). This is the only situation in which I can see you getting better formal time complexity.

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