0

I am writing a function in C++ that will evaluate a vector with n integers. Every integer has one duplicate value somewhere in the vector with the exception of one single integer that has NO duplicates. The function should return that one int with no duplicate values in the array.

I managed to make a working function that I think runs in either O(nlogn) time or in O(n^2), I'm not sure which. I need the function to run in O(n) time, how can I change my function to achieve such run time?

int singleNumber(vector<int>& nums)
{
    int s = nums.size();

    for (int i = 0; i < s; i++)
    {
        int current = i;  // current int in vector being evaluated
        bool f1 = false, f2 = false;

        for (int j = 0; j < s; j++)
        {
            if (current == nums[j] && !f1)  // if one instance of current is found
                f1 = true;
            else if (f1 && current == nums[j]) // if 2nd instance of current is found
                f2 = true;
        }

        if (f1 && !f2)    // if only one instance of current is found
            return current;
    }


}
Joshua Vaughan
  • 347
  • 3
  • 7
  • 16

1 Answers1

3

I think that you'll end up with your number if you do an xor over all elements.

Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625