Find duplicate element in array in time O(n)

前端 未结 24 2981
余生分开走
余生分开走 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 11:09

    //This is similar to the HashSet approach but uses only one data structure:

        int[] a = { 1, 4, 6, 7, 4, 6, 5, 22, 33, 44, 11, 5 };
    
        LinkedHashMap map = new LinkedHashMap();
    
        for (int i : a) {
            map.put(i, map.containsKey(i) ? (map.get(i)) + 1 : 1);
        }
    
        Set> es = map.entrySet();
        Iterator> it = es.iterator();
    
        while (it.hasNext()) {
            Entry e = it.next();
            if (e.getValue() > 1) {
                System.out.println("Dupe " + e.getKey());
            }
        }
    

提交回复
热议问题