Removing Duplicate Value from Array in Java
In this post, we’ll explore how to remove duplicate values from an array in Java using a HashMap. The HashMap is a powerful tool for this task because it only allows unique keys, which makes it easy to filter out duplicates.
Input:
8
[2,4,6,1,7,2,4,8]
Output:
1 2 4 6 7 8
CODE
import java.util.*;
class HelloWorld {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
HashMap<Integer,Integer> map=new HashMap<Integer,Integer>();
int n=sc.nextInt();
for(int i=0;i<n;i++){
int temp=sc.nextInt();
if(!map.containsKey(temp)){
map.put(temp,1);
}
}
int arr[]=new int[map.size()];
int j=0;
for (Map.Entry<Integer, Integer> e : map.entrySet())
arr[j++]=e.getKey();
for(int i=0;i<j;i++){
System.out.print(arr[i]);
}
}
}
Explanation
Input:
- The program first reads the size of the array,
n. - It then reads the array elements.
- The program first reads the size of the array,
Using a HashMap to Filter Duplicates:
- A HashMap is used to store each number as a key.
- If a number is already in the map (
map.containsKey(temp)), it is ignored. - Otherwise, the number is added to the map with a placeholder value (e.g.,
1).
Creating a New Array:
- After filtering, the unique numbers (keys of the HashMap) are transferred to a new array.
Sorting the Unique Values:
- The
Arrays.sort()method is used to sort the array of unique values.
- The
Output:
- The sorted unique values are printed.
Example Input and Output
Input:
Process:
- Original Array: [2, 4, 6, 1, 7, 2, 4, 8]
- After removing duplicates: [2, 4, 6, 1, 7, 8]
- After sorting: [1, 2, 4, 6, 7, 8]
Output:
How This Works
HashMap Filters Duplicates:
- The HashMap automatically ensures that only unique numbers are stored as keys.
Efficient Transfer:
- The unique numbers are transferred from the HashMap to an array using a simple loop.
Sorting:
- The
Arrays.sort()method sorts the array in ascending order efficiently.
- The
Key Points
Time Complexity:
- Inserting elements into a HashMap is O(1) on average.
- Sorting the array is O(n log n), where
nis the number of unique elements.
Space Complexity:
- The HashMap and the new array require extra space proportional to the number of unique elements.
Edge Cases:
- Empty Array: If the input size
nis0, the program will produce no output. - All Elements Are the Same: The program will output a single element.
- Input: [5, 5, 5, 5]
Output:5
- Input: [5, 5, 5, 5]
- Empty Array: If the input size
Sorted Output:
- The program sorts the unique values before printing them. If sorting is not required, you can skip the
Arrays.sort()step.
- The program sorts the unique values before printing them. If sorting is not required, you can skip the
No comments:
Post a Comment