JAVA - 如何找到在2D阵列以行和列重复值? [英] JAVA - How to find duplicate values in rows and columns in a 2D Array?

查看:198
本文介绍了JAVA - 如何找到在2D阵列以行和列重复值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个二维数组,我想找到一个更简单的方法来处理我的code,这样它会发现,如果没有在列,更简单的方法重复的话我有什么如下:

I have a 2D Array and I would like to find an easier way to manipulate my code so that it will find if there is a duplicate in the column and easier way then what I have below:

for (int i=0; i < array.length; i++) {
    for (int j=0; j < array.length; j++) {
        for (int k=1; k < array.length; k++){
            if (array[j+k][i] == array[j][i]) {
               if (array[j][i] != 0) {
                return true;
               }
            }
        }
    } 
  }  
return false;

编辑:请指出以上^^将无法正常工作或者作为它会抛出越界异常的退出

这路有太多的循环,我相信一定有找到重复的,而不是通过这种大规模的循环过程会更简单的方法。

This way has too many loops and I am sure there must be an easier way to find duplicates rather than going through this massive looping process.

这是一个方形的二维数组,即得。与行数=列的一个阵列。

This is for a square 2D array, ie. an array with rows = columns.

如果是这样,怎么能这个新的工作方式 - 我怎么可以操纵它的工作在行找到重复的值以及

If so, how can this new way work - and how can I manipulate it to work to find duplicate values in the rows as well.

感谢您的帮助。

推荐答案

您可以使用 HashSet的来存储所有已经遇到过的元素。应该是这样的:

you can use HashSet to store all already encountered elements. should be something like this:

static boolean noDupes(int[][] array) {
    for (int i=0; i < array.length; i++) {
        HashSet<Integer> set = new HashSet<Integer>();
        for (int j=0; j < array.length; j++) {
            if (set.contains(array[j][i])) return false;
            set.add(array[j][i]);
        }
    }
    return true;
}

结果,这个解决方案是O(长度^ 2)= 0(n),其中n是矩阵总大小。我认为这是大的O方面理想的,因为你需要检查所有元素。


this solution is O(length^2) = O(n) where n is the matrix total size. I think it is ideal in terms of big O, because you need to check all elements.

这篇关于JAVA - 如何找到在2D阵列以行和列重复值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆