簡體   English   中英

在兩個整數數組中查找公共元素java

[英]finding common elements in two integer arrays java

該代碼不止一次返回 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));

    }
}

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

這是一個 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;
}

我看到您的代碼存在以下問題:

我希望它一次返回一個包含公共數字的數組!

所以你需要聲明你的方法返回一個數組。 添加方括號:

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

在您的方法中,您還必須跟蹤目前發現的所有常見元素。 您可以使用新數組或更方便的ArrayList或更方便的HashSet (因為該集合會自動消除重復項,因此您只能獲得每個公共數字一次)。 我認為您的意思是使用counter變量來跟蹤新數組中的元素數量,只是該數組尚不存在。

你檢查:

if (tempCounter == 1) {

如果數字在b出現不止一次,這是不對的。 而是做

if (tempCounter > 0) {

正如我所說,您需要一種方法來從a過濾掉重復項,這樣您就不會得到[2, 2, 7, 7, 2, 4]而只有[2, 7, 4] 您可以使用我提到的集合 I,或者您可以使用ArrayList.contains()或引入另一個循環來檢查數字是否已經在您的常用數字數組中。 如果是,請不要再次添加它。

最后,要打印數組的內容,請使用Arrays.toString()

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

基本上來自兩個元素的公共元素的數量將是動態的。 因此,如果您嘗試將公共元素放入數組中,則不可能,因為您需要聲明此數組的大小(在這種情況下將是動態的)。

考慮使用列表。 我試圖保持邏輯盡可能簡單以及全面的變量名稱。

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

使用 Java 的 O(m+n) 解決方案提供了出色的集合數據結構。 關鍵是.retainAll()使用的.retainAll()函數,它保留了所有公共元素:

值得一提的是, retainAll()可與任何 Collection 類一起使用,並在其內部調用 contains()。 因此,O(m+n) 僅在此處的集合是 HashSet 時才為 O(m+n),因為它提供 0(1) 查找。 如果是線性的,比如List,復雜度為0(n^2)

public class common {
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);
}
    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] +" ");
            }
        }
    }

使用 HashSet 消除復雜性

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

在此處輸入圖片說明

以下是一個簡單的 O(n) 解決方案,它考慮到數組已排序。 如果沒有,您可以對它們進行排序。 這是對@talshahar 提供的解決方案的改進,它還涵蓋了最后一個常見元素(邊緣情況)。

public List<Integer>  getCommon(int[]array1, int[] array2){
    int p1 = 0;
    int p2 = 0;
    ArrayList<Integer> common = new ArrayList<Integer>();
    while(p1<array1.length || p2<array2.length) {       ​
       ​if (array1[p1] == array2[p2]) {
           ​common.add(array1[p1]);
           ​p1++;p2++;
       ​}
      ​
       ​else if (array1[p1] < array2[p2]) {
           ​p1++;
       ​} else {
           ​p2++;
       ​}
   ​}
    return common;
}

時間復雜度 o(n),即使用單個 for 循環來獲取數組中的公共元素。

    int[] arr1 = { 1, 2, 5, 5, 8, 9, 7, 10 };
    int[] arr2 = { 1, 0, 6, 5, 6, 4, 7, 0 };

    System.out.println("Array1 : " + Arrays.toString(arr1));
    System.out.println("Array2 : " + Arrays.toString(arr2));

    int i = 0;
    for (int j = 0; j < arr2.length; j++) {
        if (arr1[i] == (arr2[j])) {
            System.out.println("Common element is : " + (arr1[i]));
        }
        i++;
    }

輸出:

Array1 : [1, 2, 5, 5, 8, 9, 7, 10]
Array2 : [1, 0, 6, 5, 6, 4, 7, 0]
Common element is : 1
Common element is : 5
Common element is : 7

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM