Last active
June 13, 2017 15:01
-
-
Save anil477/1b0500dda06ebb336615f0035a5b3d49 to your computer and use it in GitHub Desktop.
Remove duplicate from an Array - using hset and in Place
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.*; | |
import java.util.*; | |
class removeDuplicate | |
{ | |
public static void main (String[] args) | |
{ | |
removeDuplicate obj = new removeDuplicate(); | |
obj.approachTwo(); | |
obj.approachOne(); | |
} | |
public void approachTwo() | |
{ | |
// this approach requires the array to be sorted. for this eg code we are taking a sorted array | |
int[] a = new int[]{1, 1, 1, 2, 2, 2, 3, 4, 4, 5, 5}; | |
int i = 1, j = 0, length = a.length; | |
while(i < length) { | |
if(a[i] == a[j]) { | |
i++; | |
} else { | |
j++; | |
a[j] = a[i]; | |
i++; | |
} | |
} | |
System.out.println("Array after removing duplicate approach two :"); | |
for(int k =0; k < j+1; k++) { | |
System.out.println(a[k]); | |
} | |
} | |
public void approachOne() | |
{ | |
int[] a = new int[]{1, 1, 1, 2, 2, 2, 3, 4, 4, 5, 5}; | |
Set<Integer> s = new HashSet<Integer>(); | |
// since we are not sure what will be the size of the new array after removing duplciate we use ArrayList | |
List<Integer> b = new ArrayList<Integer>(); | |
for(int value:a) { | |
if(s.contains(value)) { | |
continue; | |
} | |
s.add(value); | |
b.add(value); | |
} | |
System.out.println("Array after removing duplicate approach one:"); | |
for(int value:b) { | |
System.out.println(value); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment