我试图获得两个相同数组元素之间的最短距离。
输入[2,3,4,6,7,3,2]
正确输出4为什么? 因为int数组3 = a [1],a [5]和5-1 = 4,同时其他相同的值是远的。
输出实际为0
这是我的代码。
<ng2-ui-tile data-ng-repeat="component in catalogFilterdItems|
entityFilter:checkboxesFilter | filter:search |
orderBy:sortBy:reverse | limitTo:numberOfItemToDisplay" data-ng-
init="component.filterTerm = component.name + ' ' +
component.description + ' ' + component.tags.toString() + ' ' +
component.version;" [component]="component" (on-tile-
click)="gui.isLoading || goToComponent(component)" class="ng-scope"
id="NG2_UPGRADE_11_0" ng-version="2.4.10" _nghost-txp-54=""><div
_ngcontent-txp-54="" class="sdc-tile sdc-tile-fix-width">
<div _ngcontent-txp-54="" class="sdc-tile-header blue">
<!--template bindings={}-->
<!--template bindings={}--><div _ngcontent-txp-54="">S</div>
</div>
<div _ngcontent-txp-54="" class="sdc-tile-content" data-tests-id="dashboard-Elements">
<div _ngcontent-txp-54="" class="sdc-tile-content-icon">
<div _ngcontent-txp-54="" class="sprite-services-icons defaulticon" data-tests-id="Test 1 for Tenant OAM"></div>
</div>
<div _ngcontent-txp-54="" class="sdc-tile-content-info">
<div _ngcontent-txp-54="" class="sdc-tile-info-line title" data-tests-id="Test 1 for Tenant OAM">
<multiline-ellipsis _ngcontent-txp-54="" classname="w-sdc-tile-multiline-ellipsis" _nghost-txp-1=""><div _ngcontent-txp-1="" class="multiline-ellipsis-container w-sdc-tile-multiline-ellipsis" style="max-height: calc(58.8px);">
<div _ngcontent-txp-1="" class="multiline-ellipsis-content" style="max-height: calc(78.4px);">
Test 1 for Tenant OAM
<div _ngcontent-txp-1="" class="multiline-ellipsis-dots" style="top: calc(117.6px - 100%);"></div>
</div>
</div></multiline-ellipsis>
</div>
<div _ngcontent-txp-54="" class="sdc-tile-info-line subtitle" data-tests-id="Test 1 for Tenant OAMVersion">V 1.9</div>
</div>
</div>
<div _ngcontent-txp-54="" class="sdc-tile-footer">
<div _ngcontent-txp-54="" class="sdc-tile-footer-content">
<div _ngcontent-txp-54="" class="sdc-tile-footer-text">In Design Check Out</div>
</div>
</div>
</div>
</ng2-ui-tile>
为什么在进入第二个for循环后minDistance变为0?
答案 0 :(得分:1)
在您的代码中,您正在运行
if(distance<minDistance)
{
minDistance = distance;
}
在内部for循环中。无论a[i]==a[j]
是否运行,它都会运行,因此第一次运行循环时,无论a[i]==a[j]
检查如何,距离的默认值0都将应用于最小距离。
要修复,请在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;
}
}
}