这实际上是我向软件职位应聘者提出的问题之一:在锯齿状数组中找到最大数。数组的每个元素可以是一个数字,也可以是不定级别的其他数字数组,如下所示:
var ar = [2, 4, 10, [12, 4, [100, 99], 4], [3, 2, 99], 0];
现在,为了好玩和保持这篇文章的简短,我将提供两个问题的解决方案。第一个解决方案使用递归,而第二个解决方案使用堆栈。事实上,所有这些递归问题也可以通过使用堆栈方法来解决。
解决方案一:使用递归找到最大值
// Use recursion to find the maximum numeric value in an array of arrays
function findMax1(ar)
{
var max = -Infinity;
// Cycle through all the elements of the array
for(var i = 0; i < ar.length; i++)
{
var el = ar[i];
// If an element is of type array then invoke the same function
// to find out the maximum element of that subarray
if ( Array.isArray(el) )
{
el = findMax1( el );
}
if ( el > max )
{
max = el;
}
}
return max;
}
解决方案二:使用堆栈找到最大值
// Use a stack to find the maximum numeric value in an array of arrays
function findMax2(arElements)
{
var max = -Infinity;
// This is the stack on which will put the first array and then
// all the other sub-arrays that we find as we traverse an array
var arrays = [];
arrays.push(arElements);
// Loop as long as are arrays added to the stack for processing
while(arrays.length > 0)
{
// Extract an array from the stack
ar = arrays.pop();
// ... and loop through its elements
for(var i = 0; i < ar.length; i++)
{
var el = ar[i];
// If an element is of type array, we'll add it to stack
// to be processed later
if ( Array.isArray(el) )
{
arrays.push(el);
continue;
}
if ( el > max )
{
max = el;
}
}
}
return max;
}
请随意优化上述代码。您也可以通过gist on github 找到此代码。