find unique values in an array

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());
        }

    }

}

 

posted @ 2014-11-15 03:37  zmiao  阅读(194)  评论(0编辑  收藏  举报