简体   繁体   English

搜索二维数组中的重复项

[英]Searching duplicates in 2 dimensional array

I have 2 dimensional array like : 我有像二维数组:

{2 , 6 , 46, 8 , 7 , 25, 64 , 9 , 10},
{6 , 10, 50, 12, 11, 29, 68 , 13, 14},
{46, 50, 90, 52, 51, 69, 108, 53, 54}

How can I find the duplicate elements like '6', '46' and '50' ? 如何找到重复的元素,例如'6', '46' and '50'

My code finds consecutive duplicates: 我的代码找到连续的重复项:

    for (int i = 0; i < a2.length; i++) {
        for (int j = 0; j < a2[i].length; j++) {
            cursor = a2[i][j];

            if(j + 1 < a2[i].length){
                if(cursor == a2[i][j + 1]){
                    System.out.println(cursor + "has duplicate in this array");
                }
            }
        }
    }

Iterate through all elements and save it in a temporary set. 遍历所有元素并将其保存在临时集中。
When you encounter a duplicate, the list will contain it. 当您遇到重复项时,列表中将包含该重复项。

import java.util.HashSet;
import java.util.HashSet;

public class HelloWorld
{
  public static void main(String[] args)
  {
    int[][] arr = {
      {2 , 6 , 46, 8 , 7 , 25, 64 , 9 , 10},
      {6 , 10, 50, 12, 11, 29, 68 , 13, 14},
      {46, 50, 90, 52, 51, 69, 108, 53, 54}
    };

    HashSet<Integer> elements = new HashSet<>();
    HashSet<Integer> duplicates = new HashSet<>();
    for (int i = 0; i < arr.length; i++) {
        for (int j = 0; j < arr[i].length; j++) {
            if(elements.contains(arr[i][j])) {
                duplicates.add(arr[i][j]);
            }
            elements.add(arr[i][j]);
        }
    }

    System.out.println(duplicates.toString());
  }
}

Output: 输出:

[50, 6, 10, 46] [50,6,10,46]

Try this code:- 试试这个代码:

import java.util.Arrays;
import java.util.List;

public class ArrayTest {

    public static void main(String[] args) {

        Integer[][] myarray = new Integer[][]{
                  { 10, 20, 30, 40 },
                  { 50, 77, 60, 70 },
                  { 33, 22, 88, 99 },
                  { 21, 66, 65, 21 } 
                };
        int i,j;
        for(i=0;i<myarray.length;i++)
        {
            for(j=0;j<myarray.length;j++)
            {
                int temp= myarray[i][j];
                 myarray[i][j]=0;
                 List<Integer> rowvalues = Arrays.asList(Arrays.asList(myarray).get(i));
                 Boolean b=rowvalues.contains(temp) ;
                 if(b==true)
                 {
                     System.out.println("duplicate at ["+i+"]["+j+"] is: "+temp);
                 }
                 myarray[i][j]=temp;
            }
        }




    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM