【问题标题】:Find duplicate elements in 2d array在二维数组中查找重复元素
【发布时间】:2015-07-26 22:38:38
【问题描述】:

假设我有一个 3*3 数组(二维数组):

1 2 4

1 5 7

2 4 8

所以 1,2 和 4 出现了不止一次。我想要得到的结果是 3。 我该怎么做?

【问题讨论】:

标签: java


【解决方案1】:

这是一种蛮力直接计算重复项的方法。将二维数组转换为一维数组 (List<Integer>),然后循环遍历一维数组,在找到重复项时对它们进行计数并删除它们,这样就不会重复计算它们。

public static void main(String[] args) throws Exception {
    int[][] _2dArray = {
        { 1, 2, 4 },
        { 1, 5, 7 },
        { 2, 4, 8 }
    };

    // Convert to a flat 1d array
    List<Integer> flatArray = new ArrayList();
    for (int[] row : _2dArray) {
        for (int col : row) {
            flatArray.add(col);
        }
    }

    // Count and remove duplicates as you find them
    int dupCount = 0;
    for (int i = 0; i < flatArray.size(); i++) {
        boolean dupFound = false;
        for (int j = i + 1; j < flatArray.size(); j++) {
            if (flatArray.get(i) == flatArray.get(j)) {
                dupFound = true;
                // Remove duplicate found in inner loop
                flatArray.remove(j);
                j--;
            }
        }

        if (dupFound) {
            dupCount++;
            // Remove duplicate found in outer loop
            flatArray.remove(i);
            i--;
        }
    }
    System.out.println(dupCount);
}

结果:

3

Java 8 流

如果您对流感兴趣,也可以走这条路。它将数组中的所有数字组合成一个映射,其中数字是键,该数字的频率是值。然后,我们只保留值 > 1 的键/值对(重复项)。

public static void main(String[] args) throws Exception {
    int[][] _2dArray = {
        { 1, 2, 4 },
        { 1, 5, 7 },
        { 2, 4, 8 }
    };

    // Convert to a flat 1d array
    int[] flatArray = Arrays.stream(_2dArray)
        .flatMapToInt(Arrays::stream)
        .toArray();

    //Count duplicates
    Object[] duplicates = Arrays.stream(flatArray).boxed()
            // Group all integers together
            .collect(Collectors.groupingBy(i -> i, Collectors.counting()))
            // Keep key/value pairs whose value > 1
            .entrySet()
            .stream()
            .filter(entry -> entry.getValue() > 1)
            .toArray();

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

结果:

3

【讨论】:

    【解决方案2】:

    这是在二维矩阵中查找重复元素计数的解决方案不使用集合 公共类 DuplicateElementsCountIn2DMetrixWithoutUsingCollections{

    public static void main(String args[]){
        String[][] matrix = {{"1","2","1","3",},{"7","6","null","2",},{"5","6","3","null",},{"3","10","9","5",}};
        System.out.println(findDuplicate(matrix));
    }
    
    public static int findDuplicate(String[][] matrix){
        String strArr[] = new String[(matrix.length)*(matrix[0].length)];
        int count = 0;
        for(int i = 0; i < matrix.length; i++){
            for(int j = 0; j < matrix[0].length; j++){
                for(int k = 0; k < matrix.length; k++){
                    for(int l = 0; l < matrix[0].length; l++){
                        if((i!=k || j!=l)){
                            if(matrix[i][j] == matrix[k][l]){
                                int x = 0;
                                boolean flag = false;
                                while(strArr[x] != null){
                                    if(null != matrix[i][j] && matrix[i][j].equals(strArr[x])){
                                        flag = true;                                    
                                    }
                                    x++;
                                }
                                if(flag==false){
                                    strArr[count] = matrix[i][j];
                                    count++;
                                }
                            }
                        }
                    }
                }
            }
        }
        return count;
    }
    

    }

    输出

    6

    注意:1、2、3、6、null在矩阵中是重复的,因此计数为6

    【讨论】:

      猜你喜欢
      • 2017-04-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-09
      相关资源
      最近更新 更多