Question: Write a Java program that gets a one - dimensional integer array and return the count of unique elements in the array. You will write

Write a Java program that gets a one-dimensional integer array and return the count of unique elements in the array. You will write a method numUnique() that takes in the array and returns the count.
For example,
Enter the number of elements you want to store: 8 Enter the elements of the array: 42312321 Original array length: 8 Array elements are: 42312321 The number of unique elements is: 4
One way to find similar elements would be to use nested loops and/or multiple arrays. But there's a nifty trick we can use: sort the array and then check for adjacent elements. For example, in the example above the original array is:
42312321
Sorted, this array will be:
11222334
Now we can compare elements next to each other. Let's start with array[i] where i is 0, our first unique value (i.e., the value 1). If its successor, array[i+1] is the same, then we wouldn't count it since it's not unique. We'd continue this process of comparing adjacent values until we've processed the entire array.
Great, but sorting?? No problem! Use Arrays (import java.util.Arrays)--that class we used before with its .toString() method. Look up how to use its .sort() method.

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Programming Questions!