import java.util.Arrays;
public class RemoveDuplicates {
public static void main(String[] args) {
int[] arr = {13, 2, 3, 21, 4, 5, 18, 5, 6, 9, 13, 18};
int[] newArr = removeDuplicates(arr);
System.out.println(Arrays.toString(newArr));
}
public static int[] removeDuplicates(int[] arr) {
int[] tempArr = new int[arr.length];
int index = 0;
for (int i = 0; i < arr.length; i++) {
boolean isDuplicate = false;
for (int j = 0; j < index; j++) {
if (arr[i] == tempArr[j]) {
isDuplicate = true;
break;
}
}
if (!isDuplicate) {
tempArr[index++] = arr[i];
}
}
int[] newArr = new int[index];
for (int i = 0; i < index; i++) {
newArr[i] = tempArr[i];
}
return newArr;
}
}
[13, 2, 3, 21, 4, 5, 18, 6, 9]
removeDuplicates
method takes an integer array as input and returns a new array with all the duplicate elements removed.tempArr
with the same size as the input array. It then iterates through the input array, and for each element, it checks if it is a duplicate by comparing it with the elements in the tempArr
array. tempArr
array and increments the index
variable.newArr
with the correct size (i.e., the number of unique elements), copies the elements from the tempArr
array to the newArr
array, and returns the newArr
.