一個數組,含有重復元素,給出兩個數num1和num2,求這兩個數字在數組中出現的位置的最小距離
O(n)時間復雜度,O(1)空間復雜度
[cpp]
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;
}
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;
}