java 在两个整数数组中查找公共元素java

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40632887/
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-11-03 05:21:51  来源:igfitidea点击:

finding common elements in two integer arrays java

javaarrays

提问by Barry Reeves

The code returns 0 and the common numbers more than once. I want it to return an array with the common numbers once! So how do I return an arraywith numbers that are common to both arrays. I want to return {2,7,4} - something like this. I keep getting out of bounds exceptions when I try to return an array. Thanks, Barry

该代码不止一次返回 0 和公共数字。我希望它返回一个包含公共数字的数组一次!那么如何返回一个数组,其中包含两个数组共有的数字。我想返回 {2,7,4} - 像这样。当我尝试返回一个数组时,我不断遇到越界异常。谢谢,巴里

public class Test {
    public int findCommonElement(int[] a, int[] b){
        int counter=0;
        int temp= 0;
        int tempCounter = 0;
        for(int i=0; i<a.length; i++){
            temp=a[i];
            tempCounter=0;
            for(int j=0; j<b.length; j++){
                if (temp==b[j]){
                    tempCounter++;  
                }

            }

            if (tempCounter == 1) {
                temp = a[i];

                counter++;

                System.out.println(temp);

            }

        }

        return 0;
    }

    public static void main(String []args){
        int myArray[] = {2,2,7,7,2,1,5,4,5,1,1};
        int myArray2[] = {2,3,4,7,10};


        Test hello = new Test ();
        System.out.println(hello.findCommonElement(myArray, myArray2));

    }
}

回答by nail fei

an alternative solution for findCommonElement method

替代解决方案 findCommonElement method

public int[] findCommonElement(int[] a, int[] b){
    List<Integer> array = new LinkedList<Integer>();
    Set<Integer> set = new HashSet<Integer>();
    for(int ele:a){
        set.add(ele);
    }

    for(int ele:b){
        if(set.contains(ele)){
            array.add(ele);
        }
    }

    int[] arr = new int[array.size()];
    for(int i = 0; i < array.size();i++){
        arr[i] = array.get(i);
    }
    return arr;
}

回答by talshahar

here is an O(m+n) solution:

这是一个 O(m+n) 解决方案:

static ArrayList<Integer> commonElements(int[] array1, int[] array2) {
    int p1 = 0;
    int p2 = 0;
    ArrayList<Integer> common = new ArrayList<Integer>();

    while(true) {
        if (array1[p1] == array2[p2]) {
            common.add(array1[p1]);
        }
        if (p1 == array1.length - 1 || p2 == array2.length - 1) break;
        if (array1[p1 + 1] < array2[p2 + 1]) {
            p1++;
        } else {
            p2++;
        }
    }
    return common;
}

回答by shd293

O(m+n) solution with usage of Java Provided excellent Collection Data Structures. The key being .retainAll() function used in Hashset , which retains all the common elements:

使用 Java 的 O(m+n) 解决方案提供了出色的集合数据结构。关键是 Hashset 中使用的 .retainAll() 函数,它保留了所有公共元素:

It is worth mentioning that retainAll() works with any of the Collection class and internally calls contains() on it. Hence, O(m+n) will only be if the collection here is HashSet since it gives 0(1) lookup. If it is a linear one, like List, complexity will be 0(n^2)

值得一提的是,retainAll() 可与任何 Collection 类一起使用,并在其内部调用 contains()。因此,O(m+n) 仅当这里的集合是 HashSet 时才会是,因为它给出了 0(1) 查找。如果是线性的,比如List,复杂度为0(n^2)

public class common {

public static void main(String[] args){

public static void main(String[] args){

Integer[] arr1 = new Integer[]{1,1,3,4,6,6,7,2,2};
Integer[] arr2 = new Integer[]{1,1,3,2,4,8,9,5,6};
List<Integer> alist = Arrays.asList(arr1);
List<Integer> blist = Arrays.asList(arr2);

HashSet<Integer> aset =  new HashSet<>(alist);
aset.retainAll(blist);

System.out.println(aset);

}

}

回答by Manjunath Jakkandi

    int arr1[] = {1,2,5,7,89,3};
    int arr2[] = {1,45,87,34,3};

    for(int i=0;i<arr1.length;i++) {
        for(int j=0;j<arr2.length;j++) {
            if(arr1[i] == arr2[j]) {
                System.out.print(arr1[i] +" ");
            }
        }
    }

回答by Ole V.V.

I see the following issues with your code:

我看到您的代码存在以下问题:

I want it to return an array with the common numbers once!

我希望它返回一个包含公共数字的数组一次!

So you need to declare that your method returns an array. Add square brackets:

所以你需要声明你的方法返回一个数组。添加方括号:

public int[] findCommonElement(int[] a, int[] b) {

Inside your method you must also keep track of all common elements found so far. You may use a new array or more conveniently an ArrayListor even more conveniently a HashSet(since the set automatically eliminates duplicates so you get each common number only once). I think you meant the countervariable to keep track of the number of elements in the new array, only the array is not there yet.

在您的方法中,您还必须跟踪目前发现的所有常见元素。您可以使用新数组或更方便的 anArrayList或什至更方便的 a HashSet(因为该集合会自动消除重复项,因此您只能获得每个公共数字一次)。我认为您的意思是使用counter变量来跟踪新数组中的元素数量,只是该数组尚不存在。

You check:

你检查:

if (tempCounter == 1) {

This is not right if the number occurs more than once in b. Instead do

如果该数字在b. 而是做

if (tempCounter > 0) {

As I said, you need a way to filter away duplicates from aso you don't get [2, 2, 7, 7, 2, 4]but only [2, 7, 4]. You may use a set I as I mentioned, or you may use ArrayList.contains()or introduce another loop to check whether the number is already in your array of common numbers. Just don't add it again if it is.

正如我所说,您需要一种方法来过滤掉重复项,a这样您就不会得到[2, 2, 7, 7, 2, 4]但只有[2, 7, 4]. 您可以使用我提到的集合 I,或者您可以使用ArrayList.contains()或引入另一个循环来检查数字是否已经在您的常用数字数组中。如果是,请不要再次添加它。

Finally, to print the contents of an array, use Arrays.toString():

最后,要打印数组的内容,请使用Arrays.toString()

    System.out.println(Arrays.toString(hello.findCommonElement(myArray, myArray2)));

回答by Mrudav Shukla

Basically the number of common element from the two elements will be dynamic. Hence if you try to put common elements into an array then it won't be possible as you need to declare size of this array (which in this case will be dynamic).

基本上来自两个元素的公共元素的数量将是动态的。因此,如果您尝试将公共元素放入数组中,则不可能,因为您需要声明此数组的大小(在这种情况下将是动态的)。

Consider using list. I've tried to keep the logic as simple as possible along with comprehensive variable names.

考虑使用列表。我试图保持逻辑尽可能简单以及全面的变量名称。

    import java.util.ArrayList;
    import java.util.Iterator;
    import java.util.List;

    public class Test {

    public static void main(String[] args) {

        int myArray[] = { 2, 2, 7, 7, 2, 1, 5, 4, 5, 1, 1 };
        int myArray2[] = { 2, 3, 4, 7, 10 };

        Test hello = new Test();
        System.out.println(hello.findCommonElement(myArray, myArray2));
    }
    /**
     * 
     * @param a
     * @param b
     * @return commonElements
     */
    public List<Integer> findCommonElement(int[] a, int[] b) {

        List<Integer> commonElements = new ArrayList<Integer>();

        for(int i = 0; i < a.length ;i++) {
            for(int j = 0; j< b.length ; j++) {
                    if(a[i] == b[j]) {  
                    //Check if the list already contains the common element
                        if(!commonElements.contains(a[i])) {
                            //add the common element into the list
                            commonElements.add(a[i]);
                        }
                    }
            }
        }
        return commonElements;
    }
}

回答by Keshav Gera

Remove Complexity Using HashSet

使用 HashSet 消除复杂性

Finding common elements in two integer arrays in java

在java中查找两个整数数组中的公共元素

import java.util.*;
public class Complexity
{
    public static void main(String args[])
    {
    int arr1[] = {2,2,7,7,2,1,5,4,5,1,1};
        int arr2[] = {2,3,4,7,10};

        HashSet<Integer> hashset= new HashSet<Integer>();

        for (int i : arr1){
            hashset.add(i);
        }
        for (int i : arr2) 
        {
            if (hashset.contains(i))
        {
            // found duplicate!   
                System.out.println("Common Elements --> " +i );
        }
       }
    }
}

enter image description here

在此处输入图片说明

回答by Ishan Lakshitha

int x[] = {5, 3, 7, 2, 8}; int y[] = {6, 3, 8, 0, 2, 7, 4, 9};

int x[] = {5, 3, 7, 2, 8}; int y[] = {6, 3, 8, 0, 2, 7, 4, 9};

    for (int i = 0; i < x.length; i++) {
        for (int j = 0; j < y.length; j++) {
            if (x[i] == y[j]) {
                System.out.println(x[i]);
            }
        }
    }