Find duplicates in integer array with borders

Below is a description of the problem and the algorithm that I wrote. What can be done to improve this algorithm?

For an integer array of unknown size containing only numbers from 0 to 30, write a function to return an integer array containing all duplicates.

int[] findDupes(int[] array) {
    int[] found = new int[30];
    int[] dupes = new int[30];
    int dupesCount = 0;
    for (int i = 0; i < array.length; i++) {
        if (found[array[i]] <= 1) {
            found[array[i]]++;              
        }else{
            continue;
        }
        if(found[array[i]] > 1){
            dupes[dupesCount++] = array[i];
            if (dupesCount == 30)
                break;
        }
    }
    if (dupesCount == 0)
        return new int[0];
    return dupes;
}

Suppose the best option for running this algorithm is n or 30, depending on which is lower and the worst case for running this algorithm is n, since I have to scan the entire array to find duplicates. Any comments?

+3
source share
4 answers

here is a modified version with built-in comments.

int[] found = new int[3];
    int[] dupes = new int[3];
    int dupesCount = 0;
    for (int i = 0; i < array.length; i++) {
        if (found[array[i]] <= 1) {
            found[array[i]]++;              
        }
        if(found[array[i]] > 1){ //duplicate found
            dupes[dupesCount++] = array[i];

            // if 30 duplicate are found don't scan the array any more
            // since the distinct numbers are only 30
            if (dupesCount == 30) 
                break;
        }
    }
    if (dupesCount == 0)
        return null;
    return dupes;
0

, , ,

    if(found[array[i]] > 1){
        dupes[dupesCount++] = array[i];
        if (dupesCount == 30)
            break;
    }

?

, 1000 0.

? 0.

30. , ?

+2

. 1 2 ? 0 3 ?

1 2 , 1 30; BitSet , . , , 0, , .

+1

- :

    if (found[array[i]] <= 1)              
    }else{
        continue;//happens if found[array[i]] > 1
    }
    if(found[array[i]] > 1){//usually don't get here, because of continue

? , .

Do you need to return an array of length 30 if there is only one duplicate?

I suggest making your code slower and better by breaking up tasks.

0
source

Source: https://habr.com/ru/post/1758616/


All Articles