This is the first solution to remove the duplicate numbers from an Array of integers. This program takes the temporary array to store the numbers after removing the duplicates.
import java.util.Arrays;
public class DuplicateNumbersRemoval {
public static void main(String[] args) {
// TODO Auto-generated method stub
int [] arrNums= {23,44,13,754,128,23,200,44};
int targetIdx=0,upperBound;
int [] arrTarget = new int[arrNums.length];
System.out.println("The original Array given below");
dispArr(arrNums,arrNums.length);
System.out.println("The original Array below after sorting");
Arrays.sort(arrNums);
dispArr(arrNums,arrNums.length);
//Compare the successive elements of original array and store the unique number into the target array
for (int i=0;i<arrNums.length;i++) {
if ((i+1) == arrNums.length) {
upperBound=arrNums.length-1;
arrTarget[targetIdx++]=arrNums[i];
}
else
upperBound=i+1;
if (arrNums[i] == arrNums[upperBound])
continue;
else
arrTarget[targetIdx++]=arrNums[i];
}
System.out.println("The final Array after removing the duplicate numbers is below");
dispArr(arrTarget, targetIdx);
}
public static void dispArr(int [] tempArr, int idxTmp) {
System.out.print("[ ");
for(int i=0;i<idxTmp;i++)
System.out.print(tempArr[i]+" ");
System.out.println("]");
}
}
The original Array given below
[ 23 44 13 754 128 23 200 44 ]
The original Array below after sorting
[ 13 23 23 44 44 128 200 754 ]
The final Array after removing the duplicate numbers is below
[ 13 23 44 128 200 754 ]

Leave a comment