寻找数组内两个数的最小距离

/*
寻找数组内两个数的最小距离。
比如:

int a[] = {1,2,3,4,5,3,2,4,7,8,9,6,4,4,3};

n1 = 4, n2 = 8, 则,这两个数在数组a中的最小距离是2。

变成求解!
*/

#include<stdio.h>

int getDistance(int a[],int len,int n1,int n2)
{
int ret=len;
int i=0;
int preIndex1=-1;
int preIndex2=-1;
for(i=0;i<len;i++)
{
if(a[i]==n1)
{
if(preIndex2>=0)
{
int cd=i-preIndex2;
cd=(cd>0)?cd:-cd;
if((0<cd)&&(cd<ret))
{
ret=cd;
}
}
preIndex1=i;
}


if(a[i]==n2)
{
if(preIndex1>=0)
{
int cd=i-preIndex1;
cd=(cd>0)?cd:-cd;
if((0<cd)&&(cd<ret))
{
ret=cd;
}
}
preIndex2=i;
}
}
return ret;
}

int main()
{
int tx=0;
int a[] = {8,2,3,9,4,3,2,4,7,3,2,8,4,4,3};
tx=getDistance(a,sizeof(a)/sizeof(int),4,8);
printf("%d ",tx);
return 1;
}

原文地址:https://www.cnblogs.com/txzing/p/13959007.html