I am writing a method to remove an adjacent duplicate value in an ArrayList of Integer.
public static void remove2InARow(ArrayList<Integer> list) {
for (int i = 0; i < list.size() - 1; i ) {
if (list.get(i) == list.get(i 1)) {
list.remove(i);
}
}
}
If you passed in [3,4,3,3]
as a parameter, the output would be [3,4,3]
.
This implementation becomes problematic when the same value is repeated more than 2 times. For example, [1, 2, 5, 4, 6, 6, 6, 1, 2]
becomes [1, 2, 5, 4, 6, 6, 1, 2]
when it should be [1, 2, 5, 4, 6, 1, 2]
. Similarly, [n, ..., n]
should become [n]
.
Is there a way to adapt my implementation to be recursive? Does it even need to be recursive?
CodePudding user response:
It certainly does not need to be recursive!
The source of your problem is that removing elements from a collection while iterating over it can lead to some unexpected behaviour, try not to touch the list while iterating over it, then once you're done - remove the elements you need to.
CodePudding user response:
import java.util.stream.Collectors;
public static void remove2InARow(ArrayList<Integer> list) {;
list= list.stream().distinct().collect(Collectors.toList());
System.out.println(list);
}
Maybe it'll help you!
CodePudding user response:
public static void remove2InARow(ArrayList<Integer> list) {
for (int i = 0; i < list.size() - 1; i ) {
if (list.get(i) == list.get(i 1)) {
list.remove(i);
i--;
}
}
}
This worked for me.