Removing duplicates from an array is a common programming task. In this blog post, we'll explore different methods to achieve this in Java, focusing on unsorted arrays.
1. Using a HashSet
A HashSet is a collection that stores unique elements. By adding all elements of the array to a HashSet, we can effectively remove duplicates.
import java.util.HashSet;
import java.util.Set;
public class RemoveDuplicates {
public static int[] removeDuplicates(int[] arr) {
Set<Integer> set = new HashSet<>();
for (int num : arr) {
set.add(num);
}
int[] result = new int[set.size()];
int i = 0;
for (int num : set) {
result[i++] = num;
}
return result;
}
public static void main(String[] args) {
int[] arr = {1, 2, 3, 2, 1, 4, 5, 4};
int[] uniqueArr = removeDuplicates(arr);
System.out.print("Array with duplicates removed: ");
for (int num : uniqueArr) {
System.out.print(num + " ");
}
}
}
Time Complexity: O(n)
2. Using Two Pointers
This approach iterates through the array and maintains two pointers:
* i: The current index.
* j: The index for the next unique element.
public class RemoveDuplicates {
public static int[] removeDuplicates(int[] arr) {
int j = 0;
for (int i = 0; i < arr.length; i++) {
boolean isDuplicate = false;
for (int k = 0; k < i; k++) {
if (arr[i] == arr[k]) {
isDuplicate = true;
break;
}
}
if (!isDuplicate) {
arr[j++] = arr[i];
}
}
int[] result = new int[j];
System.arraycopy(arr, 0, result, 0, j);
return result;
}
// ... (main method as in the previous example)
}
Time Complexity: O(n^2)
3. Sorting and Removing Duplicates
This method first sorts the array and then iterates through it, removing adjacent duplicates.
import java.util.Arrays;
public class RemoveDuplicates {
public static int[] removeDuplicates(int[] arr) {
Arrays.sort(arr);
int j = 0;
for (int i = 0; i < arr.length - 1; i++) {
if (arr[i] != arr[i + 1]) {
arr[j++] = arr[i];
}
}
arr[j++] = arr[arr.length - 1];
int[] result = new int[j];
System.arraycopy(arr, 0, result, 0, j);
return result;
}
// ... (main method as in the previous example)
}
Time Complexity: O(n log n) due to sorting
Choosing the Best Method:
* HashSet: Most efficient for general cases due to its constant-time average lookup.
* Two Pointers: Suitable for smaller arrays or when you need to avoid additional data structures.
* Sorting: Efficient if the array is already partially sorted or if you need the output to be sorted.
By understanding these methods, you can choose the most appropriate approach for your specific needs and optimize your code accordingly.
This Content Sponsored by Buymote Shopping app
BuyMote E-Shopping Application is One of the Online Shopping App
Now Available on Play Store & App Store (Buymote E-Shopping)
Click Below Link and Install Application: https://buymote.shop/links/0f5993744a9213079a6b53e8
Sponsor Content: #buymote #buymoteeshopping #buymoteonline #buymoteshopping #buymoteapplication
No comments:
Post a Comment