How to find duplicate elements in array in effective way? I mean to say with very less iterations

戏子无情 提交于 2021-01-10 08:20:17

问题


How to find the duplicate element in an array which is having lacks of elements? If I iterate the array for lacks of times the performance will became slow. What is the best way to iterate an array in efficient way? Or else can we use any other Java collection object to find the duplicates with less number of iterations or less time complexity?


回答1:


You can use a HashSet because Sets don't allow duplicates, just loop over array of elements and insert them into a HashSet using the add() method. If the add() method returns back false then that element already exists in the set and it is there for your duplicate. This way you only loop over the array once which results in a time and space complexity of O(n).




回答2:


It depends on the task conditions, the first approach is faster, and the last one is slower:

Character[] chars = {'A', 'A', 'B', 'B', 'B', 'C'};
  1. If you want to filter certain elements and get count of them:

    Long countB = Arrays.stream(chars)
            .filter(ch -> ch.equals('B')).count();
    
    System.out.println(countB); // 3
    
  2. If you want to get an array of distinct elements:

    Character[] distinct = Arrays.stream(chars)
            .distinct().toArray(Character[]::new);
    
    System.out.println(Arrays.toString(distinct)); // [A, B, C]
    

    Or you can use HashSet:

    HashSet<Character> set = new HashSet<>(Arrays.asList(chars));
    
    System.out.println(set); // [A, B, C]
    
  3. If you want to collect a map of duplicates:

    Map<Character, Long> duplicates = Arrays.stream(chars)
            .collect(Collectors.groupingBy(ch -> ch, Collectors.counting()));
    
    System.out.println(duplicates); // {A=2, B=3, C=1}
    


来源:https://stackoverflow.com/questions/65335482/how-to-find-duplicate-elements-in-array-in-effective-way-i-mean-to-say-with-ver

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!