Reputation: 11
I need to write a java method unique that takes an arbitrary integer array and return an array with the same integers but no duplicates. Would I have to create the array inside the unique method ? and Would I have to declare arr1, arr2, and arr3 as well?
public static int[] unique(){
int [] arr1;
int [] arr2;
int [] arr3;
for(int i= 0; i < arr1.length; i++) {
}
}
public static void main(String[] args) {
int[] arr1 = {34, 34, 10, 50, 56, 34, 67, 34};
int[] arr2 = {23, 100, 5, 56, 67, 10, 10, 10, 34, 67};
int[] arr3 = {25, 25, 25, 25};
System.out.println(Arrays.toString(unique(arr1)));
1
System.out.println(unique(arr1).length);
System.out.println(Arrays.toString(unique(arr2)));
System.out.println(unique(arr2).length);
System.out.println(Arrays.toString(unique(arr3)));
System.out.println(unique(arr3).length);
}
}
Upvotes: 1
Views: 398
Reputation: 3297
From Your question what i understand is : you want to create a method that takes an array as parameter and return another containing no duplicate values of the first array.
So what comes directly to mind is using Set ( which is a collection of non duplicated
values).
Here you can solve your problem either by checking Array values manually or using a set :
public static int[] unique(int [] array){
Set<Integer> set = new HashSet<>(Arrays.asList(array)); // create a set from your array
// set now containing non duplicate value
return set.toArray(new int[set.size()]); // then convert your set to an array and return it.
}
Upvotes: 0
Reputation: 816
First, put all the values into a Set<Integer>
, which by default don't allow duplicate values, then add all the values you have in your Set<Integer>
to an int[]
and return it.
public static int[] unique(int[] values) {
Set<Integer> uniqueValuesSet = new HashSet<>();
for(Integer value : values) {
uniqueValuesSet.add(value);
}
int i = 0;
int[] uniqueValuesArray = new int[uniqueValuesSet.size()];
for(Integer value : uniqueValuesSet) {
uniqueValuesArray[i++] = value;
}
return uniqueValuesArray;
}
Upvotes: 1