问题
Without a for loop
, is there any way to see if a value exists in a multidimensional array
? I found
Arrays.asList(*ArrayName*).contains(*itemToFind*)
but that will only search the first dimension of the array, and I need to search 2 dimensions.
回答1:
I created an 5x5 Integer array and intialized with value i*j.
Exists
method takes a row number and value to search for.
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);
}
回答2:
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)
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)
回答3:
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
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.
来源:https://stackoverflow.com/questions/23069740/check-if-value-exists-in-a-multidimensional-array-java