arrays - 在数组数组(或列表列表等)中查找指定元素的深度

标签 arrays algorithm multidimensional-array pseudocode

我必须创建一个函数(使用伪代码)返回数组中指定元素的深度(内部有可选数组),例如:

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/

相关文章:

algorithm - 在不泄露来源的情况下比较 secret 数据

java - 如何按照列表描述的顺序有效地处理HashMap?

c - 在 C 中释放多维数组

java - 对于不同类型的数据,我应该使用哪个 Map 类?

javascript - AngularJs - 将 2 个关键相似的数组合并为 1 个 ng-repeat

ios - 将 double 组附加到 Swift 中的邮件

c++ - 有哪些合理的方法可以改进递归问题的解决?

python - 高效计算 Khatri-Rao 类总和(成对行总和)

c - 尝试更改 C 中二维数组中的元素

java - 在二维数组中查找相邻元素并计算它们。