【问题标题】:Detect duplicate values in primitive Java array检测原始 Java 数组中的重复值
【发布时间】:2011-07-18 20:39:53
【问题描述】:

我想检测 Java 数组中的重复值。例如:

int[] array = { 3, 3, 3, 1, 5, 8, 11, 4, 5 };

我如何获得特定的重复条目以及它出现了多少次?

【问题讨论】:

  • 您在寻找哪些价值观? 3s 还是 5s?
  • 我正在尝试查找 3 和 5 以及它们出现的时间。

标签: java arrays duplicates primitive


【解决方案1】:

我将有一个Map<Integer, Integer>,其中第一个整数是数组中出现的数字的value,第二个整数是count(出现次数)。

  • 循环运行array.length
  • 对于数组中的每一项,执行map.containsKey(array[i])。如果地图中存在数字,则增加该数字(类似于map.put(array[i], map.get(array[i]) + 1)。否则,在地图中创建一个新条目(例如map.put(array[i], 1)
  • 最后,遍历 map 并检索 value 大于 1 的所有键。

【讨论】:

  • @yannis hristofakis,不。这是一个错字。修正了我帖子中的错误。
【解决方案2】:

看起来像是一个名为 multiset 的数据结构的工作。

Multiset<Integer> mp = HashMultiset.create();
mp.addAll(Arrays.asList(new Integer[] { 3, 3, 3, 1, 5, 8, 11, 4, 5 }));

标准 JDK 6 是原始的,不包含 multiset。如果您不想重写它,可以使用预先存在的库,例如 Google Guava-libraries 或 Apache Commons。

例如,您可以使用 Guava 库

    for (Integer i : mp.elementSet())
        System.out.println(i + " is contained " + mp.count(i) + " times.");

这会输出:

1 is contained 1 times.
3 is contained 3 times.
4 is contained 1 times.
5 is contained 2 times.
8 is contained 1 times.
11 is contained 1 times.

【讨论】:

    【解决方案3】:

    答案取决于源数组中的数字范围。如果范围足够小,您可以分配一个数组,遍历您的源并在源编号的索引处递增:

    int[] counts = new int[max_value + 1];
    
    for (int n: array) {
        counts[n]++;
    }
    

    如果您的源数组包含未知或太大的范围,您可以创建一个Map 并计算在内:

    Map<Integer,Integer> counts = new HashMap<Integer,Integer>();
    
    for (Integer n: array) {
        if (counts.containsKey(n)) {
            counts.put(n, counts.get(n) + 1);
        } else {
            counts.put(n, 1);
        }
    }
    

    注意。在没有 JVM 帮助的情况下键入上述内容,留下了错别字 作为读者的练习:-)

    【讨论】:

      【解决方案4】:
      public class Duplicate {
      
          public static void main(String[] arg) {
              int[] array = {1, 3, 5, 6, 2, 3, 6, 4, 3, 2, 1, 6, 3};
      
              displayDuplicate(array);
      
          }
      
          static void displayDuplicate(int[] ar) {
              boolean[] done = new boolean[ar.length];
              for(int i = 0; i < ar.length; i++) {
                  if(done[i])
                      continue;
                  int nb = 0;
                  for(int j = i; j < ar.length; j++) {
                      if(done[j])
                          continue;
                      if(ar[j] == ar[i]) {
                          done[j] = true;
                          nb++;
                      }
                  }
                  System.out.println(ar[i] + " occurs " + nb + " times");
              }
          }
      }
      

      【讨论】:

      • 请不要用代码回答明显的作业问题。给出提示或其他东西——除了为他做作业之外的任何东西。是的,看看问题的性质以确定这是一个家庭作业问题,他们不会总是标记它。
      • 我只是指出这一点,因为人们通常都渴望提供帮助,并且有时并不真正考虑问题的性质。
      【解决方案5】:
      import java.util.HashMap;
      import java.util.Iterator;
      import java.util.Map;
      
      public class DuplicatedValuesInArray 
      {
      
          public static void main(String args[]) {  
              int[] array = { 3, 3, 3, 1, 5, 8, 11, 4, 5 };
              Map<Integer, Integer> map= new HashMap<Integer, Integer>();
      
            for(int i=0;i<array.length;i++) {   
                if(map.containsKey(array[i]))
      
                map.put(array[i],map.get(array[i]) + 1);
            else
                map.put(array[i], 1);
            }
      
            for (Integer i : map.keySet()) {
                System.out.println(i + " is contained " + map.get(i) + " times.");
            }
         }
      }
      

      【讨论】:

        【解决方案6】:

        您可以使用 Collectors.frecuency() 和 Collectors.groupingBy。

        我就是这样做的,希望对你有帮助。

            Map<Object,Long> finalValues = new HashMap<Object, Long>();
        
            finalValues = Arrays.asList(new Integer[] {3, 3, 3, 1, 5, 8, 11, 4, 5 })
                    .stream()
                    .collect(Collectors.groupingBy(e -> e, Collectors.counting()));
        
            //Check the output
            finalValues.entrySet().forEach(entry -> {
                System.out.println("number: " + entry.getKey() + "| Times: "+ entry.getValue());
            });
        

        输出是:

        number: 1| Times: 1
        number: 3| Times: 3
        number: 4| Times: 1
        number: 5| Times: 2
        number: 8| Times: 1
        number: 11| Times: 1
        

        你甚至可以使用频率来删除所有不重复的数字:

        Map finalValues = new HashMap();

            List<Integer> numbers = Arrays.asList(new Integer[]{1,2,1,3,4,4});     
        
            finalValues = numbers
                    .stream()
                    .filter(x-> Collections.frequency(numbers, x) > 1)
                    .collect(Collectors.groupingBy(e -> e, Collectors.counting()));
        
            //Check the output
            finalValues.entrySet().forEach(entry -> {
                System.out.println("number: " + entry.getKey() + "| Times: "+ entry.getValue());
            });
        

        输出是:

        number: 1| Times: 2
        number: 4| Times: 2
        

        【讨论】:

          【解决方案7】:

          为第一步分配一个计数器,然后您可以将它们与另一个数组相关联,将每个数字分配给一个索引,然后如果您的数字重复,则增加您的计数器...

          【讨论】:

            【解决方案8】:

            对数组进行排序,然后扫描它或Arrays.binarySearch + 在任一方向扫描。由于分配更少且没有包装,这可以更快,尤其是在更大的数组上。

            【讨论】:

              【解决方案9】:
               Java 8, the solution:
              1. Create Map when the Key is the Value of Array and Value is counter.
              2. Check if Map contains the Key increase counter or add a new set.
              private static void calculateDublicateValues(int[] array) {
                    //key is value of array, value is counter
                    Map<Integer, Integer> map = new HashMap<Integer, Integer>();
              
                    for (Integer element : array) {
                      if (map.containsKey(element)) {
                        map.put(element, map.get(element) + 1); // increase counter if contains
                      } else
                        map.put(element, 1);
                    }
              
                    map.forEach((k, v) -> {
                      if (v > 1)
                        System.out.println("The element " + k + " duplicated " + v + " times");
                    });
              
                  }
              

              【讨论】:

              • 此答案不跟踪重复值出现的次数。您还可以对代码的作用添加一些解释吗?
              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 2013-02-08
              • 2015-05-09
              • 2010-11-13
              相关资源
              最近更新 更多