I tried this for loop but when for duplicated element in the array the inner loop breaks and if more than 10 repeated element are place in the array then the outer-loop brakes.
I need to return an array of same object type since I need to use the methods to pick some values from it.
public Mode insT(Guide[] guide){
Guide[] guideVo = checkGuideDuplication(guide);
}
public Guide[] checkGuideDuplication (Guide[] guide){
for(int i = 0; i<guide.length-1; i ){
for(int j = i 1; i<guide.length; i ){
if(guide[i].getGuide().trim().equals(guide[j].getGuide().trim())){
guide = (Guide[]) ArrayUtils.remove(guide);
}
}
}
return guide;
}
CodePudding user response:
You need to reset the inner index once you remove an element so it gets checked (and bounds-checked) again:
guide = (Guide[]) ArrayUtils.remove(guide);
j--;
You can avoid the inner loop entirely if you use a map to weed out duplicates:
public Guide[] checkGuideDuplication (Guide[] guide){
Map<String, Guide> uniques = new HashMap<>();
for(Guide g : guide){
uniques.putIfAbsent(g.getGuide().trim(), g);
}
return uniques.values().toArray(new Guide[0]);
}
CodePudding user response:
The most performing O(N) solution would be to use Map
as shown in shmosel's answer.
But if using Map
is not an option due to some constraints/limitations (e.g. only arrays are allowed), another solution would be to set removed elements to null
and count the number of deletions, then shift null
s to the end of the array and return a truncated array:
public Guide[] checkGuideDuplication (Guide ... guide) {
int deleted = 0;
for (int i = 0; i < guide.length-1; i ) {
if (null == guide[i]) {
continue;
}
String currGuide = guide[i].getGuide().trim();
for(int j = i 1; j < guide.length; j ) {
if (null == guide[j]) {
continue;
}
if (currGuide.equals(guide[j].getGuide().trim())) {
guide[j] = null;
deleted ;
}
}
}
// shift remaining elements
for (int i = 0, j = 0; i < guide.length; i ) {
if (guide[i] != null) {
guide[j ] = guide[i];
}
}
return Arrays.copyOf(guide, guide.length - deleted);
}