Coding Interview Questions: No. 58 - Search in Adjacent Numbers
{
if (nums == nullptr || length <= 0)
return -1;
int index = 0;
while (index < length && nums[index] != target)
{
int delta = target - nums[index];
index += abs(delta);
}
if (index < length)
return index;
return -1;
}
Read full article from Coding Interview Questions: No. 58 - Search in Adjacent Numbers
Question: Given an array where two neighboring elements are adjacent (in absolute difference 1), can you write an algorithm to search an element in the array and return its position? If the element appears multiple times, please return the first occurrence.
Analysis: The most simple and straightforward solution is to traverse the array and compare elements one by one. This strategy works for every array, and it does not utilize the property of the array where two neighboring elements are in absolute difference 1.
We begin from the first element of the element, and compare it with the given number. If the absolute difference is n, move to the right by distance n. Then we compare the current visited element. Repeat until the given element is found, or the position is beyond the length of the array when the given element is not available.
int findFirst(int* nums, int length, int target){
if (nums == nullptr || length <= 0)
return -1;
int index = 0;
while (index < length && nums[index] != target)
{
int delta = target - nums[index];
index += abs(delta);
}
if (index < length)
return index;
return -1;
}
Read full article from Coding Interview Questions: No. 58 - Search in Adjacent Numbers