一个数组,含有重复元素,给出两个数num1和num2,求这两个数字在数组中出现的位置的最小距离
O(n)时间复杂度,O(1)空间复杂度
int minDistance(int A[], int size, int num1, int num2)
{
int num1_last_pos = -1;
int num2_last_pos = -1;
int min_dist = INT_MAX;
for(int i = 0; i < size; ++i)
{
if(A[i] == num1)
{
num1_last_pos = i;
if(num2_last_pos >= 0)
min_dist = min(min_dist, num1_last_pos-num2_last_pos);
}
if(A[i] == num2)
{
num2_last_pos = i;
if(num1_last_pos >= 0)
min_dist = min(min_dist, num2_last_pos-num1_last_pos);
}
}
return min_dist;
}