javascript - 使用嵌套函数查找第二大数。查找最大数的函数是覆盖原始数组
问题描述
嗨,我应该创建一个返回第二大数字的函数。我开始这样做是为了运行该函数以找到最大的数字。然后我想从我的数组中省略那个最大的数字并再次运行相同的函数。我只被允许使用循环。推送、弹出切片、索引、循环和条件
我尝试过切换循环的位置并使用变量。我尝试改变事物的范围。我还考虑创建一个新的空数组变量,运行一个循环并将所有不是最大的项目推入那里,然后在该数组上运行最大数字函数。
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。我认为这是因为当我尝试定义变量“最大”时,原始参数数组发生了变化。
解决方案
排序很浪费。我们可以使用线性空间和时间来确定第二大数 -
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
推荐阅读
- python - 我无法让我的不和谐机器人发送链接
- mongodb - 根据项目在另一个集合中被引用的次数对项目进行排序
- apache-spark - 通过使用 EMR 的 livy 会话执行语句时出现导入错误
- android - Android:将边距设置为可绘制单选按钮的左侧
- python - 在 Django 中使用基于函数的视图阻止不需要的用户访问其他用户的配置文件数据
- python - 我如何提交多个表格?
- scikit-image - 使用 skimage 进行水平和垂直膨胀
- sql-server - 启动 Spring Boot 应用程序时出错,面临与 Hikari Pool 相关的问题
- python - 如何将带有字典的数据框列转换为行和列?
- javascript - 为什么相同类型的两个组件之间共享状态?