检查多维数组中是否存在值java
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23069740/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Check if value exists in a multidimensional array java
提问by user2956947
Without a for loop
, is there any way to see if a value exists in a multidimensional array
? I found
没有 a for loop
,有没有办法查看 a 中是否存在值multidimensional array
?我发现
Arrays.asList(*ArrayName*).contains(*itemToFind*)
but that will only search the first dimension of the array, and I need to search 2 dimensions.
但这只会搜索数组的第一个维度,我需要搜索 2 个维度。
采纳答案by deanosaur
I created an 5x5 Integer array and intialized with value i*j.
Exists
method takes a row number and value to search for.
我创建了一个 5x5 整数数组并用值 i*j 初始化。
Exists
方法需要一个行号和值来搜索。
private static Integer[][] myarray = new Integer[5][5];
public static boolean exists(int row, int value) {
if(row >= myarray.length) return false;
List<Integer> rowvalues = Arrays.asList(Arrays.asList(myarray).get(row));
if(rowvalues.contains(value)) return true;
return exists(row+1, value);
}
回答by Alexandre Santos
Yes.
是的。
You can use Bloom filters (http://en.wikipedia.org/wiki/Bloom_filter) or create a tree-based index for the keys of your Array, such as a Trie (http://en.wikipedia.org/wiki/Trie)
您可以使用布隆过滤器 ( http://en.wikipedia.org/wiki/Bloom_filter) 或为数组的键创建基于树的索引,例如 Trie ( http://en.wikipedia.org/wiki /特里)
Basically you'd need a data structure to look for the values, and not for the keys. It would not cost much space or speed since you could re-use the references of the value objects on both data structures (yours and the one you elect)
基本上你需要一个数据结构来查找值,而不是键。它不会花费太多空间或速度,因为您可以在两种数据结构(您的和您选择的)上重复使用值对象的引用
回答by zgc7009
You can do almost anything with recursion if you care to headache your way through the logic of it. In this case it shouldn't be too hard
如果您想通过递归的逻辑来解决问题,您几乎可以用递归做任何事情。在这种情况下应该不会太难
private boolean checkForValue(int val, int row, int col){
if(row == numRows && col == numCols)
return false;
else{
if(values[row][col] == val)
return true
else if(col < (numCols - 1))
checkForValue(val, row, col + 1);
else
checkForValue(val, row + 1, 1);
}
}
However, if you are just wanting to save time I think the for loop really is pretty efficient to start
但是,如果您只是想节省时间,我认为 for 循环确实非常有效
private boolean checkForValue(int val){
for(int i = 0; i < numRows; i++){
for(int j = 0; j < numCols; j++){
if(values[i][j] == val) return true;
}
}
}
return false;
Neither is too rough.
两者都不太粗糙。