我必须创建一个函数(使用伪代码)返回数组中指定元素的深度(内部有可选数组),例如:
def array[] = {"a", {"b", {"c"}, "d"}, {{{}}}, "e"};
对于“e”它应该返回 0,对于“c”它应该返回 2 等等。 如果数组中没有指定的元素,函数应该返回-1。
我已经尝试了几次,但我不知道优雅(和工作..)的解决方案,只有这个:
func foo(array[], var element) {
int depth = 0;
boolean found = false;
boolean recursion = false;
boolean foundInRecursion = false;
for (int i = 0; i < array.length; i++) {
if (array[i] instanceof array[]) {
depth++;
recursion = true;
foo(array[i], element);
recursion = false;
} else if (array[i] == element) {
if (recursion) {
foundInRecursion = true;
} else {
found = true;
}
}
}
if (foundInRecursion) {
return depth;
} else if (found){
return 0;
} else {
return -1;
}
}
如果有任何帮助,我将不胜感激! 谢谢
最佳答案
在你的伪代码中:
func depth(array[], var element) {
/* this function returns how deep the element is in the given array */
for (int i = 0; i < array.length; i++) {
current = array[i]
if current == element {
return 0; // element is right in the array we are given
}
if (current instanceof array[]) {
// Whoa, subarray! How deep our element is in it?
subdepth = depth(current, element)
if subdepth >= 0 {
// Element was found in *sub*-array, so add 1 to the depth
return subdepth + 1;
}
}
}
// If we are here, we found nothing
return -1;
}
关于arrays - 在数组数组(或列表列表等)中查找指定元素的深度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42424381/