c++ - 两个相同阵列元素之间的最短距离
问题描述
我试图获得两个相同数组元素之间的最短距离。
输入 [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?
解决方案
在您的代码中,您正在运行
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;
}
}
}
推荐阅读
- botframework - 为 Bot 任务模块的 AdaptiveCard 创建自定义元素
- google-apps-script - 从 google doc app 脚本创建 PDF 文件
- axios - 如何在 React Hooks 中的单击按钮上显示组件?
- python - 如何使用OpenCV检测文字图片并使代码停止
- c# - 尝试获取 TabViewItem 的子项,但始终不返回任何内容
- javascript - for循环中全局声明的var关键字(Javascript)
- python - 使用 'with' 调用 dunder 方法
- ubuntu - FreeRadius 未启动
- javascript - 将变量传递给 mapDispatchToProps 中的操作
- php - 无法删除php中的记录