Say i've got an array:
int[] numbersArray = new int[]{10, 20, 20, 10, 10, 30, 50, 10, 20};
I'd like to return the count of pair of the numbers that are the same and remove them from my array.
Result of the method when numbersArray is passed should be 3. I'm stuck with my solution.
n - the number of elements in array
ar - given int[] array
public static int myMethod(int n, int[] ar) {
int pairs=0;
List<Integer> myList = new ArrayList<>();
for(int i : ar) {
myList.add(i);
System.out.println(i);
}
for(int i=0; i<n-1; i++) {
for(int j=i+1; j<n-2; j++) {
if (myList.get(i) == myList.get(j)) {
pairs++;
System.out.println(pairs);
myList.remove(i);
myList.remove(j);
}
}
}
return pairs;
}
edit:
im getting IndexOutOfBoundsException even though I deducted 1 while looping + the problem seems to be occuring when I'm trying to remove j element (the one that matches i). I'd like to remove both of them from my array which should increase my pairs variable by 1.