检测原始 Java 数组中的重复值

发布于 2024-10-23 19:06:17 字数 129 浏览 3 评论 0原文

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

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

如何获取特定的重复条目以及它出现的次数?

I want to detect duplicate values in a Java array. For example:

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

How could I get the specific duplicated entry and how many times it occurs?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

心奴独伤 2024-10-30 19:06:17

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

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

I'll have a Map<Integer, Integer> where the first integer is the value of the number that occurs in the array and the second integer is the count (number of occurrence).

  • Run through the array.length in a loop
  • for each item in the array, do a map.containsKey(array[i]). If there exists a number in a map, increment that number (something like map.put(array[i], map.get(array[i]) + 1). Otherwise, create a new entry in a map (e.g map.put(array[i], 1).
  • Finally, iterate through the map and retrieve all keys where value is greater than 1.
仙女 2024-10-30 19:06:17

看起来像是一个名为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-libraries,您可以

    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.

Seems like a job for data structure called multiset.

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

Standard JDK 6 is primitive and do not contain multiset. If you do not want to rewrite it, you can use preexisting library like Google Guava-libraries or Apache Commons.

For example with Guava-libraries you can

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

And this would output:

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.
妄司 2024-10-30 19:06:17

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

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 帮助的情况下输入上述内容,剩下的就是消除拼写错误
作为读者的练习:-)

The answer depends on the number range in your source array. If the range is small enough you can allocate an array, loop through your source and increment at the index of your source number:

int[] counts = new int[max_value + 1];

for (int n: array) {
    counts[n]++;
}

If your source array contains an unknown or too large range, you can create a Map and count in that:

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

NB. typed the above without the help of a JVM, getting rid of typoes is left
as an exercise for the reader :-)

¢好甜 2024-10-30 19:06:17
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");
        }
    }
}
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");
        }
    }
}
骄傲 2024-10-30 19:06:17
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.");
      }
   }
}
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.");
      }
   }
}
爱殇璃 2024-10-30 19:06:17

您可以使用 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

You can use Collectors.frecuency() and Collectors.groupingBy.

This is how i do this, hope this can help you.

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

The output is:

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

You can even use frecuency to delete all the numbers that doesn't repeat:

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

The output is :

number: 1| Times: 2
number: 4| Times: 2
雨的味道风的声音 2024-10-30 19:06:17

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

assign a counter for the first step then you can relate them to an another array assigning each number to an index then if your number is duplicated increment your counter...

躲猫猫 2024-10-30 19:06:17

对数组进行排序,然后扫描它或 Arrays.binarySearch + 沿任一方向扫描。由于分配量少得多并且没有包装,因此速度会更快,尤其是在较大的数组上。

Sort the array, then either scan it or Arrays.binarySearch + scan in either direction. Due to much fewer allocations and no wrapping, this can be faster, especially on larger arrays.

扬花落满肩 2024-10-30 19:06:17
 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");
      });

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

    }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文