Practice Exercise 1.2

Source Code

public class DuplicateChecker {

    public static boolean containsDuplicates(int[] numbers) {
        for (int i = 0; i < numbers.length; i++) {
            for (int j = 0; j < numbers.length; j++) {
                if (i != j && numbers[i] == numbers[j]) return true;
            }
        }
        return false;
    }

    public static void main(String[] args) {
        // Worst case scenario: No duplicates
        int[] numbersWorstCase = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
        long startTimeWorstCase = System.nanoTime();
        System.out.println("Contains duplicates (Worst Case)? " + containsDuplicates(numbersWorstCase));
        long endTimeWorstCase = System.nanoTime();
        System.out.println("Execution time (Worst Case): " + (endTimeWorstCase - startTimeWorstCase) + " ns");

        // Best case scenario (practically): Duplicate at the beginning
        int[] numbersBestCase = {2, 2, 3, 4, 5, 6, 7, 8, 9, 10};
        long startTimeBestCase = System.nanoTime();
        System.out.println("Contains duplicates (Best Case)? " + containsDuplicates(numbersBestCase));
        long endTimeBestCase = System.nanoTime();
        System.out.println("Execution time (Best Case): " + (endTimeBestCase - startTimeBestCase) + " ns");
    }
}

Last updated