首页 > 解决方案 > 使用嵌套函数查找第二大数。查找最大数的函数是覆盖原始数组

问题描述

嗨,我应该创建一个返回第二大数字的函数。我开始这样做是为了运行该函数以找到最大的数字。然后我想从我的数组中省略那个最大的数字并再次运行相同的函数。我只被允许使用循环。推送、弹出切片、索引、循环和条件

我尝试过切换循环的位置并使用变量。我尝试改变事物的范围。我还考虑创建一个新的空数组变量,运行一个循环并将所有不是最大的项目推入那里,然后在该数组上运行最大数字函数。

var largest = 0;

var findSecondLargest = function(array) {

  for (b = array.length; b > 0; b--)
    largest = findLargest(array); {
    console.log(largest + "largest" + array)
  }
  for (n = array.length; n > 0; n--)
    if (array[n] >= largest)
      array.splice(n, 1);
    else if (array[n] > array[b])
    array.splice(n, 1);
  else if (array[n] < array[b])
    array.splice(-1, 1);
  return array;
};

var findLargest = function(array1) {
  for (x = 0; x <= array1.length; x++) {
    for (j = array1.length; j > 0; j--) {
      if (array1[j] > array1[x])
        array1.splice(x, 1);
      else if (array1[x] > array1[j])
        array1.splice(-1, 1);
    }
  }
  return (array1);
};


findSecondLargest([89, 28, 22, 20, 41, 1, 39, 41, 67]);

findSecondLargest([89, 28, 22, 20, 41, 1, 39, 41, 67]) // returns 67

这是它应该做的,但它只返回 89。我认为这是因为当我尝试定义变量“最大”时,原始参数数组发生了变化。

标签: javascriptarrays

解决方案


排序很浪费。我们可以使用线性空间和时间来确定第二大数 -

const secondLargest = (xs = []) =>
  xs.reduce
    ( ([ $0, $1 ], x) =>
        x >= $0
          ? [ x, $0 ]
      : x >= $1
          ? [ $0, x ]
      : [ $0, $1 ]
    , [ -Infinity, -Infinity ]
    )
    [1]

console.log(secondLargest([89, 28, 22, 20, 41, 1, 39, 41, 67]))
// 67


推荐阅读