Friday, May 24, 2013

Amazon Question: Find the first occurrence of an integer in an array.

Given an array of integers in which the difference between  two adjacent integers is less than or equal to 1. Find the first occurrence of an given integer. Do better than linear search.


int firstOccurence(vector < int > A, int n)
{
    int i = 0;
    int size = A.size();
    while(i < size)
    {
if(A[i] == n)
return i;

i += abs(n - A[i]);
    }
    return -1;
}

No comments:

Post a Comment