, . , .
My approach is to make it clear to the interviewer that we can solve the problem with one limitation in the function call: the caller must provide 2 pointers, from one to the beginning and the other to the end of the array. Given these 2 pointers and using basic pointer arithmetic, I achieve this solution; please let me know what you think about this.
int *findMiddleArray( int const *first, int const *last )
{
if( first == NULL || last == NULL || first > last )
{
return NULL;
}
if( first == last )
{
return (int *)first;
}
size_t dataSize= ( size_t )( first + 1 ) - ( size_t )first,
addFirst= ( size_t )first,
addLast= ( size_t )last,
arrayLen= ( addLast - addFirst) / dataSize + 1,
arrayMiddle= arrayLen % 2 > 0 ? arrayLen / 2 + 1 : arrayLen / 2;
return ( int * )( ( arrayMiddle - 1 ) * dataSize + addFirst );
}
source
share