我正在编写一些 coderbyte 代码,并注意到当我尝试获取相等值数组中的最大项时,会返回 undefined
。记录时最小值是日志 80
而不是 undefined
。这是为什么?
更新的代码:
function noRepeat(arr) {
tmp = []
if (arr.length === 2 && arr[0] === arr[1]) {
return arr;
}
for (var i = 0;i<arr.length;i++) {
if (tmp.indexOf(arr[i]) === -1) {
tmp.push(arr[i])
}
}
return tmp
}
function SecondGreatLow(arr) {
arr = noRepeat(arr).sort(function (a,b) {return a-b;});
var low = arr[arr.indexOf(Math.min.apply(Math,arr))+1];
console.log("low",low);
var high = arr[arr.indexOf(Math.max.apply(Math,arr))-1];
console.log("high",high);
return low +" "+high;
}
console.log(SecondGreatLow([80,80]));
输出:
"low" 80
"high" undefined
"80 undefined"
最佳答案
实际上,这样就可以了。您想如何在两个相似数字的数组中找到第二最大\最小的数字? 它应该输出“无解决方案”或其他内容。就像空数组没有解决方案一样。
function SecondGreatLow(arr)
{
arr = noRepeat(arr).sort(function (a,b) {return a-b;});
if (arr.length < 2)
return "No solution";
console.log("low ", arr[1]);
console.log("high ", arr[arr.length - 2]);
return low + " " + high;
}
您不需要数学最小值和最大值函数,因为您的数组已排序并且值是唯一的。您需要从开头取第二个,从结尾取第二个。
此外,您不需要这部分,因为它是通过算法正确计算的。
if (arr.length === 2)
{
return arr[1] + " " + arr[0];
}
例如,您有一个数组 [1, 1, 2]。
删除重复项并得到 [1, 2]。
现在您的算法返回 low = arr[1] = 2 和 high = arr[2 - 2] = arr[0] = 1。
答案是正确的 - 2 是第二小的数字,1 是第二大的数字。
关于javascript - 具有相等值的数组的 Math.max 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30634572/