A sorted array is passed to my method and i have to find the minimum singular value. If no such value is found the method returns 0. I have created two versions of this method. In the first version, I iterate trough the array twice which works fine but there has to be a way to find the value with one iteration. In the second version, I iterate through it once but i need it fixed so, that it works if the last index of the array is my minimum singular value e.g {1, 1, 2, 2, 3}.
//First version with two iterations
public int findMinimumSingularValue(int[] array) {
for (int i = 0; i < array.length; i++) {
int countOccurence = 0;
for (int j = 0; j < array.length; j++) {
if (array[i] == array[j]) {
countOccurence ++;
}
}
if(countOccurence == 1) {
return array[i];
}
}
return 0;
}
I've tried to implement it with only one iteration, but couldn't get it to work. Only the first version is up for review, but I'll leave my attempt at improvement here to illustrate what I have in mind:
//Second version with one iteration which needs to be fixed public int findMinimumSingularValue(int[] array) { if(array.length == 0) { return 0; } int isNotUnique = array[array.length - 1]; for (int i = 0; i < array.length; i++) { if (array[i] != array[i + 1] && array[i] != isNotUnique) { return array[i]; } isNotUnique = array[i]; } return 0; }