79.4k views
0 votes
Write a method named numUnique that accepts a sorted array of integers as a parameter and that returns the number of unique values in the array. The array is guaranteed to be in sorted order, which means that duplicates will be grouped together. For example, if a variable called list stores the following values: int[] list

User Josh Clemm
by
3.5k points

1 Answer

8 votes

Answer:

The method in Java is as follows:

public static int numUnique(int list[]) {

int unique = 1;

for (int i = 1; i < list.length; i++) {

int j = 0;

for (j = 0; j < i; j++) {

if (list[i] == list[j])

break;

}

if (i == j)

unique++;

}

return unique;

}

Step-by-step explanation:

This line defines the numUnique method

public static int numUnique(int list[]) {

This initializes the number of unique elements to 1

int unique = 1;

This iterates through the list

for (int i = 1; i < list.length; i++) {

The following iteration checks for unique items

int j = 0;

for (j = 0; j < i; j++) {

if (list[i] == list[j]) If current element is unique, break the iteration

break;

}

if (i == j)

unique++;

}

This returns the number of unique items in the list

return unique;

}

User BenAlabaster
by
3.6k points