Removing Duplicate Values in Array
import
java.util.Arrays;
import
java.util.Scanner;
public class
RemovingDuplicateArray
{
public static int
removeDuplicateElements(int arr[], int n)
{
if (n==0 || n==1){
return n;
}
int[] temp = new int[n];
int j = 0;
for (int i=0; i<n-1; i++){
if (arr[i] != arr[i+1]){
temp[j++] = arr[i];
}
}
temp[j++] = arr[n-1];
// Changing original array
for (int i=0; i<j; i++){
arr[i] = temp[i];
}
return j;
}
public static void main (String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the
number of elements you want to store: ");
int n= input.nextInt();
int[] arr= new int[n];
System.out.println("Enter the
elements of the array: ");
for(int a=0;a<arr.length;a++)
{
arr[a]=input.nextInt();
}
Arrays.sort(arr);
int length = arr.length;
length = removeDuplicateElements(arr, length);
//printing array elements
System.out.println("After Removing Dupilcate
Values");
for (int i=0; i<length; i++)
System.out.print(arr[i]+" ");
}
}
Output :
Enter the number of elements you want to
store: 5
Enter the elements of the array:
12
5
1
4
5
After Removing Dupilcate Values
1 4 5 12
Explanation :
- The code imports necessary classes for array manipulation (java.util.Arrays) and user input (java.util.Scanner).
- The code defines a public class named "RemovingDuplicateArray."
- Inside the class, there's a static method called removeDuplicateElements that takes an array of integers (arr) and its length (n) as input and returns an integer representing the new length of the array after removing duplicates.
- The removeDuplicateElements method uses a temporary array (temp) to store the non-duplicate elements. It iterates through the input array and checks if the current element is the same as the next element. If they are not the same, the current element is copied to the temporary array.
- After copying elements, the last element of the input array is copied to the temporary array since it won't be covered in the loop.
- The original array (arr) is then updated with the elements from the temporary array, ensuring that it only contains the non-duplicate elements. The method returns the new length of the array.
- The main method is the entry point of the program. It does the following:
- Takes user input for the number of elements in the array.
- Takes user input for the elements of the array.
- Sorts the array using Arrays.sort(arr).
- Calls the removeDuplicateElements method to remove duplicates and returns the new length of the array.
- Prints the array after removing duplicates.
Comments
Post a Comment