在java中查找数组中的重复值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/46419403/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 02:21:28  来源:igfitidea点击:

Find duplicate values in an array in java

javaarrays

提问by Shan

I am trying to write a code which will find the duplicate value in an array. So, far I have written below code:

我正在尝试编写一个代码来查找数组中的重复值。所以,到目前为止,我已经编写了以下代码:

public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner sc = new Scanner(System.in);
        //System.out.println("Please enter the length of Array: ");
        int[] array = new int[6];
        for(int i =0; i<array.length;i++) {
            System.out.println("Enter value for index "+i+":");
            array[i] = sc.nextInt();
            }

        FindDuplicateInArray obj = new FindDuplicateInArray();

        obj.findDupicateInArray(array);
    }

    public void findDupicateInArray(int[] a) {
        //int pointer = a[0];
        int count=0;
        for(int j=0;j<a.length;j++) {
            for(int k =j+1;k<a.length;k++) {
                if(a[j]==a[k] && j!=k && j<k && count<=1) {
                    count++;
                    if(count==1)
                    System.out.println(a[j]);

                }

            }


        }

    }

But I am not getting the expected output, for example:

但我没有得到预期的输出,例如:

  1. If I give value 1,2,1,4,3,1 then it is successfully finding the duplicate value 1.

  2. But if I provide 2 set of duplicate value in an array, still it is finding the first duplicate. e.g. 1,2,1,2,1,3. It is giving output only 1.

  1. 如果我给出值 1,2,1,4,3,1 那么它就成功地找到了重复的值 1。

  2. 但是如果我在数组中提供 2 组重复值,它仍然会找到第一个重复值。例如 1,2,1,2,1,3。它只给出输出 1。

I found the reason of incorrect result which is condition of count i.e. count is set to greater than 1 and it is not matching to first if condition.

我找到了错误结果的原因,即计数条件,即计数设置为大于 1,并且它与第一个 if 条件不匹配。

So, I have tried to reset the counter to 0 after one loop iteration, now it is giving all duplicate values but duplicate values printing twice.

因此,我尝试在一次循环迭代后将计数器重置为 0,现在它提供所有重复值,但重复值打印两次。

public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner sc = new Scanner(System.in);
        //System.out.println("Please enter the length of Array: ");
        int[] array = new int[6];
        for(int i =0; i<array.length;i++) {
            System.out.println("Enter value for index "+i+":");
            array[i] = sc.nextInt();
            }

        FindDuplicateInArray obj = new FindDuplicateInArray();

        obj.findDupicateInArray(array);
    }

    public void findDupicateInArray(int[] a) {
        //int pointer = a[0];
        int count=0;
        for(int j=0;j<a.length;j++) {
            for(int k =j+1;k<a.length;k++) {
                if(a[j]==a[k] && j!=k && j<k && count<=1) {
                    count++;
                    if(count==1)
                    System.out.println(a[j]);

                }

            }
            **count = 0;**

        }

    }

e.g. Input: 1,2,1,2,1,2, Output: 1 2 1 2

例如输入:1,2,1,2,1,2,输出:1 2 1 2

Please suggest how to get the correct result.

请建议如何获得正确的结果。

采纳答案by Kh.Taheri

You are in the right way, I have just updated your method, I hope that you will understand what was your mistake:

您走对了,我刚刚更新了您的方法,希望您能理解您的错误:

public void findDupicateInArray(int[] a) {
        int count=0;
        for(int j=0;j<a.length;j++) {
            for(int k =j+1;k<a.length;k++) {
                if(a[j]==a[k]) {
                    count++;
                }
            }
            if(count==1)
               System.out.println(a[j]);
            count = 0;
        }
    }

Nevertheless, this will make your code running correctly, and that does not mean you have written the optimal code.

尽管如此,这将使您的代码正确运行,但这并不意味着您编写了最佳代码。

回答by Alex

Please have a look in below code it will help you.

请查看下面的代码,它会对您有所帮助。

We have to count the no of repeatation of each element and then at the last find the count, which will tell the duplicate nos.

我们必须计算每个元素的重复次数,然后在最后找到计数,这将告诉重复次数。

    package com.java;

import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;

public class FindDuplicateInArray {

    public static void main(String[] args) {

        int[] intArr = new int[] { 1, 2, 1, 2, 1, 3, 4, 6, 2, 8 };

        Map<Integer, Integer> map = new LinkedHashMap<Integer, Integer>();

        for (int i = 0; i < intArr.length; i++) {
            // take first element and then matched complete array
            int temp = intArr[i];
            int count = 0;

            for (int j = 0; j < intArr.length; j++) {
                if (temp == intArr[j]) {
                    // element matched -- break
                    count++;
                }
            }
            map.put(temp, count);
        }

        Set<Integer> duplicate = new LinkedHashSet<Integer>();
        Set<Integer> noDuplicate = new LinkedHashSet<Integer>();

        for (int i = 0; i < intArr.length; i++) {
            if (map.containsKey(intArr[i])) {
                System.out.println("Key :" + intArr[i] + " Value : " + map.get(intArr[i]));

                if (map.get(intArr[i]) > 1) {
                    // means repeated character
                    duplicate.add(intArr[i]);

                } else {
                    // non repeated character
                    noDuplicate.add(intArr[i]);
                }
            }
        }

        System.out.println("Duplicate Chars : " + Arrays.toString(duplicate.toArray()));
        System.out.println("No Duplicate Chars : " + Arrays.toString(noDuplicate.toArray()));

    }

}

回答by Jaime S

Maybe it's easier to convert the array to list and make all the logic with the Java 8 streams api in one sentence:

也许更容易将数组转换为列表并在一句话中使用 Java 8 流 api 制作所有逻辑:

        Integer[] numbers = new Integer[] { 1, 2, 1, 2, 1, 3 };
    List<Integer> listInteger = Arrays.asList(numbers);         
    listInteger.stream().filter(i -> Collections.frequency(listInteger, i) >1).collect(Collectors.toSet()).forEach(System.out::println);

Output

输出

1
2

回答by oleg.cherednik

I do not like to use Streams or smth hight-level for solving algorythmic problem; only plain java. So this is my solution:

我不喜欢使用 Streams 或 smth hight-level 来解决算法问题;只有普通的java。所以这是我的解决方案:

public static Set<Integer> findDuplicateInArray(int... arr) {
    Set<Integer> unique = new HashSet<>();
    Set<Integer> duplicate = new HashSet<>();

    for (int val : arr)
        (unique.contains(val) ? duplicate : unique).add(val);

    return duplicate;
}

In case you are able to modify incomming arr, then with some small modification, you can refuce from Set<Integer> unique.

如果您能够修改 incomming arr,那么通过一些小的修改,您可以拒绝 from Set<Integer> unique