Java Array, Finding Duplicates

前端 未结 14 883
闹比i
闹比i 2020-11-22 09:13

I have an array, and am looking for duplicates.

duplicates = false;
for(j = 0; j < zipcodeList.length; j++){
    for(k = 0; k < zipcodeList.length; k++         


        
相关标签:
14条回答
  • 2020-11-22 10:05

    Initialize k = j+1. You won't compare elements to themselves and you'll also not duplicate comparisons. For example, j = 0, k = 1 and k = 0, j = 1 compare the same set of elements. This would remove the k = 0, j = 1 comparison.

    0 讨论(0)
  • 2020-11-22 10:06

    Let's see how your algorithm works:

    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.
    

    a better algorithm:

    for (j=0;j<zipcodeList.length;j++) {
        for (k=j+1;k<zipcodeList.length;k++) {
            if (zipcodeList[k]==zipcodeList[j]){ // or use .equals()
                return true;
            }
        }
    }
    return false;
    
    0 讨论(0)
提交回复
热议问题