猿问

Java数组,查找重复项

Java数组,查找重复项

我有一个数组,正在寻找副本。

duplicates = false;for(j = 0; j < zipcodeList.length; j++){
    for(k = 0; k < zipcodeList.length; k++){
        if (zipcodeList[k] == zipcodeList[j]){
            duplicates = true;
        }
    }}

但是,当没有副本时,此代码不能工作。为什么这么说?


回首忆惘然
浏览 751回答 3
3回答

萧十郎

让我们看看您的算法是如何工作的:an array of unique values:[1, 2, 3]check 1 == 1. yes, there is duplicate, assigning duplicate to true.check 1 == 2. no, doing nothing.check 1 == 3. no, doing nothing.check 2 == 1. no, doing nothing.check 2 == 2. yes, there is duplicate, assigning duplicate to true.check 2 == 3. no, doing nothing.check 3 == 1. no, doing nothing.check 3 == 2. no, doing nothing.check 3 == 3. yes, there is duplicate, assigning duplicate to true.更好的算法:for (j=0;j<zipcodeList.length;j++) {&nbsp; &nbsp; for (k=j+1;k<zipcodeList.length;k++) {&nbsp; &nbsp; &nbsp; &nbsp; if (zipcodeList[k]==zipcodeList[j]){ // or use .equals()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return true;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}return false;

素胚勾勒不出你

您可以使用位图来提高大数组的性能。&nbsp;&nbsp;&nbsp;&nbsp;java.util.Arrays.fill(bitmap,&nbsp;false); &nbsp;&nbsp;&nbsp;&nbsp;for&nbsp;(int&nbsp;item&nbsp;:&nbsp;zipcodeList) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;if&nbsp;(!bitmap[item])&nbsp;bitmap[item]&nbsp;=&nbsp;true; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;else&nbsp;break;更新:这是我在过去的一个非常疏忽的回答,把它保存在这里仅供参考。你应该参考Andersoj的优秀作品回答.
随时随地看视频慕课网APP

相关分类

Java
我要回答