Write a static method called removeMatches that removes extra copies of a value that are adjacent to it in an ArrayList of Integer objects. For example, if a variable called list contains the following: [1, 3, 3, 3, 3, 15, 2, 2, 1, 19, 3, 42, 42, 42, 7, 42, 1] and we make the following call: removeMatches (list); Then list should store the following values after the call: [1, 3, 15, 2, 1, 19, 3, 42, 7, 42, 1]
Program Code:
// Java Program to Remove Duplicate Elements
// From the Array using extra space
public class Main {
public static int removeMatches(int a[], int n)
{
if (n == 0 || n == 1) {
return n;
}
// creating another array for only storing
// the unique elements
int[] temp = new int[n];
int j = 0;
for (int i = 0; i < n - 1; i++) {
if (a[i] != a[i + 1]) {
temp[j++] = a[i];
}
}
temp[j++] = a[n - 1];
// Changing the original array
for (int i = 0; i < j; i++) {
a[i] = temp[i];
}
return j;
}
public static void main(String[] args)
{
int a[] = { 1, 3, 3, 3, 3, 15, 2, 2, 1, 19, 3, 42, 42, 42, 7, 42, 1 };
int n = a.length;
n = removeMatches(a, n);
// Printing The array elements
for (int i = 0; i < n; i++)
System.out.print(a[i] + " ");
}
}
Output:
1 3 15 2 1 19 3 42 7 42 1
Trending now
This is a popular solution!
Step by step
Solved in 2 steps with 1 images