“In an array with integers between 1 and 1,000,000 one value is in the array twice. How do you deter

You can do this in one line with C#. Not saying this is the most efficient method, but it's neat. Assuming Haircut's numbers array:

Code:
int[] numbers = { 2, 6, 8, 4, 5, 6, 9, 10, 1 };

numbers.GroupBy(n => n)
    .Where(g => g.Count() > 1)
    .Select(g => g.Key)
    .FirstOrDefault();

You would obviously want to make that safer but it will return 6 correctly :)
 
in C++11:

Use a std::unordered_set. Insert each value until the return code indicates that the value couldn't be added, i.e. it's already in there.

I'm not sure how efficient this would be but the code would be neat

Unordered set is an associative container that contains set of unique objects of type Key. Search, insertion, and removal have average constant-time complexity.

http://en.cppreference.com/w/cpp/container/unordered_set/insert
 
If that's the case then you can just sum the numbers and subtract 500,000,500,000 (the sum of all numbers from 1 - 1,000,000) from the total to find your duplicate value.

Very clever.
I never thought of that one.
This is the method I would use.
Quick and simple.

EDIT: the above assumes that each number is in the array once and only once (except for the duplicate number). If the array is of a smaller size, then you will have to resort to the "non-simple" method.
 
Last edited:
Back
Top Bottom