Answer the question
In order to leave comments, you need to log in
Explain the complexity of this algorithm?
I am studying the book "Algorithms. Theory and practical application" by Rod Stevens. There are algorithms for finding duplicates.
boolean containsDuplicate(int[] array) {
for (int i = 0; i < array.length - 1; i++) {
for (int j = i + 1; j < array.length; j++) {
if (array[j] == array[i]) {
return true;
}
}
}
return false;
}
Answer the question
In order to leave comments, you need to log in
It seems to me that the extra N at the beginning - the inner loop will run (N-1)+(N-2)+...+1 times. But in fact, you are comparing 2 numbers and if you turn to combinatorics, then you can take the first N options, and the second (N-1). Since the order is not important to us, we divide in half - this is N * (N-1) / 2
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question