find unique values in an array

时间:2023-03-08 17:56:28

Problem:

given an array that contains duplicates (except one value), find the one value that does not have a duplicate in that array. Explain the complexity of your algorithm. So in the array: A = [2, 3, 4, 5, 2, 3, 4] your algorithm should return 5 since that's the value that does not have a duplicate.

Solution:

this can be solved using a HashMap (two pass through). Or 2 HashSets (1 pass through).

I will show the 2nd solution (2 hashset)

import java.util.*;

public class Dup{

    public static void main(String[] args){
int[] n= {2,3,4,5,2,3,4,1,1,1};
Set<Integer> all= new HashSet<>();
Set<Integer> unq= new HashSet<>(); for(int i:n){
if(all.contains(i)){
unq.remove(i);
}
else{
all.add(i);
unq.add(i);
}
} Iterator i= unq.iterator();
while(i.hasNext()){
System.out.println(""+ i.next());
} } }