首页 > 解决方案 > 两个相同阵列元素之间的最短距离

问题描述

我试图获得两个相同数组元素之间的最短距离。

输入 [2,3,4,6,7,3,2]
正确输出 4 为什么?
因为 int 数组 3=a[1],a[5] 和 5-1=4,同时其他相同的值相距甚远。
实际输出为 0

这是我的代码。

int minimumDistances(vector<int> a) {
int distance=0, minDistance=(int)a.size()-1;
int prevIndex=0;
cout<<endl<<"The value ofmindistance is : "<<minDistance;
  for(int i =0; i<a.size();i++)
  {
    cout<<endl<<"The minDistance value just after entering fori : "<<minDistance;
    prevIndex=i;
    for(int j=i+1;j<a.size();j++)
    {
    if(a[i]==a[j])
    {
      //cout<<endl<<"The value of i and j is :"<<i<<"and"<<j;
      cout<<endl<<"The minDistance value just after entering forj : "<<minDistance;
      //cout<<endl<<"The values of previous indices are"<<prevIndex;
      distance =j-prevIndex;
      prevIndex=j;
      cout<<endl<<"The values of previous indices are"<<prevIndex<<"The distance and mindistances are"<<distance<<","<<minDistance;
    }
    if(distance<minDistance)
    {
      minDistance = distance;
    }

  }

}
return minDistance;
}

为什么进入第二个for循环后minDistance变为0?

标签: c++arrays

解决方案


在您的代码中,您正在运行

if(distance<minDistance)
{
      minDistance = distance;
}

在内部 for 循环中。无论是否运行,它都在运行,因此第一次运行循环时,无论检查a[i]==a[j]如何,距离的默认值 0 都将应用于最小距离。a[i]==a[j]

a[i]==a[j]要解决此问题,请在您的块中移动此 if 语句,如下所示:

for(int j = i+1; j < a.size(); j++) {
    if(a[i]==a[j]) {
        cout<<endl<<"The minDistance value just after entering forj : "<<minDistance;
        distance = j-prevIndex;
        prevIndex = j;
        if(distance < minDistance) {
            minDistance = distance;
        }
    }    
}

推荐阅读