In Java, there are many ways to remove duplicate elements from an Array or ArrayList. We can use Set or Map depending upon our requirements. But what if we have to remove duplicate elements from an Array without using classes of util package.
In this scenario, most of the people will do it using two loops without thinking the complexity.
But there are few people who thinks about complexity before writing code. They will try to reduce the complexity by using Single loop instead of two.
/*
* Remove Duplicate Elements from an Array/ArrayList without using Util classes
*/
public static void removeDuplicate(int []arr){
boolean flag = false;
int current = arr[0];
for(int i=0; i<arr.length; i++){
if(current==arr[i] && !flag){
flag = true;
}else if(current != arr[i]){
System.out.println(current+" ");
flag = false;
current = arr[i];
}
}
System.out.println(current+" ");
}
Input -
int[] arr = {1, 1, 2, 3, 4, 4, 4, 4, 5, 5, 6, 7, 7, 7, 8};
Output -
1
2
3
4
5
6
7
8
The above logic will only work for sorted array. If we have unsorted array, then sort the array before passing it to the method parameter.
No comments:
Post a Comment