I'm trying to make a method that counts the number of unique elements in an array. For example, if the array contains [1,2,3,4,5,1,5] there are 3 unique elements and my method should return the number 3.
This is what I´ve got so far:
static int numberOfUniqueIntegers(int[] number, int len) {
int unique = 0;
for (int i = 0; i < len; i++){
int j;
for (j = 0; j < i; j ++) {
if (number[i] == number[j]) {
break;
}
}
if (i == j);
unique++;
}
return unique;
}
The method takes in the array number and an integer len (which is the length of the array).
But in this case: [1,2,3,4,5,1,5] my method would return 5, instead of 3. I somehow need to check if the number has been repeated before, and if not unique++.
[1, 2, 3, 4, 5, 1, 5]:[1, 2, 3, 4, 5]. How are there only 3 ? What do you mean ?