Find duplicate element in array in time O(n)

前端 未结 24 2936
余生分开走
余生分开走 2020-11-27 10:07

I have been asked this question in a job interview and I have been wondering about the right answer.

You have an array of numbers from 0 to n-1, one o

24条回答
  •  孤城傲影
    2020-11-27 10:50

    We can do using hashMap efficiently:

    Integer[] a = {1,2,3,4,0,1,5,2,1,1,1,};
    HashMap map = new HashMap();
    for(int x : a)
    {
        if (map.containsKey(x))  map.put(x,map.get(x)+1);
        else map.put(x,1);
    }
    
    Integer [] keys = map.keySet().toArray(new Integer[map.size()]);
    for(int x : keys)
    {
        if(map.get(x)!=1)
        {
            System.out.println(x+" repeats : "+map.get(x));
        }
    }
    

提交回复
热议问题