I need to write a method where a int[] will be supplied as an input and it should return an array, but with all of the numbers that occur more than n times removed entirely.
Input:
(int list) data = [1, 2, 2, 3, 3, 3, 4, 5, 5]
Output:
(int list) [1, 4]
These are the steps i have tried:
- Copy the int array to ArrayList (inputList).
- Create a LinkedHashset to find unique values
- Iterate LH and find the collection frequency of ArrayList with iterator.
int[] intArray = new int[0];
ArrayList<Integer> inputList = new ArrayList<Integer>(data.length);
//System.out.println(Arrays.toString(data));
for (int i = 0; i < data.length; i++){
inputList.add(Integer.valueOf(data[i]));
}
LinkedHashSet<Integer> lhs = new LinkedHashSet<>(inputList);
intArray = new int[lhs.size()];
int i=0;
int j=0;
Iterator<Integer> itr = lhs.iterator();
while(itr.hasNext()){
Integer shiftNumber = itr.next();
if(Collections.frequency(inputList, shiftNumber)==1) {
intArray[i++] = shiftNumber.intValue();
j++;
}
}
intArray = Arrays.copyOf(intArray, j);
return intArray;
}
}
return intArray;
I am able to achieve the results with the above snippet.However, I need suggestions in reducing the piece of code and improving performance by using any algorithms or other collection objects.