Given array of positive items = {1, 2, 3, 4, 4} the simplest brute force solution could be as per below. However, this solution has Time complexity O(n^2)
Do you think there is better solution? Let's find out.
public class Test {
public static int find(int[] items) {
int length = items.length;
for (int i = 0; i < length; i++) {
for (int j = 0; j < length; j++) {
if (items[i] == items[j] && i != j) {
return items[i];
}
}
}
return -1;
}
}
Couple of things to discuss:
- Time Complexity https://www.studytonight.com/data-structures/time-complexity-of-algorithms
- Data structure and algorithms