Pergunta de entrevista da empresa Bloomberg

given an array, all the elements in the array appear twince, only one element appears only once. Find that element. Eg, the array is 2 4 2 3 4 1 3 6 6, 1 should be the answer.

Respostas da entrevista

Sigiloso

1 de fev. de 2012

ask what the largest possible value held in the array would be in this example, looks like 10 so let's go with that. int findDup( int a[], int n ){ // n is size of input array int temp[10] = { 0 }; for (int i = 0; i < n ; i++){ temp[a[i]] ++; } for ( i = 0; i < 10; i++) { if (temp[i] == 1) return i; } } syntax might be a bit off.. s'been a while since i programmed in c++ @_@

Sigiloso

1 de fev. de 2012

actually, there's a slightly more efficient way to implement this: int findDup( int a[], int n ){ // n is size of input array int temp[10] = { 0 }; for (int i = 0; i < n ; i++){ if(temp[a[i]] == 1) return a[i]; temp[a[i]] ++; } }

Sigiloso

13 de out. de 2014

If it is an array of integers then xor together all the elements and the result is the answer to the question. The trick here is that the duplicate elements will xor each out to zero.