JAVA - 如何找到在2D阵列以行和列重复值? [英] JAVA - How to find duplicate values in rows and columns in a 2D Array?
问题描述
我有一个二维数组,我想找到一个更简单的方法来处理我的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屋!