gpt4 book ai didi

javascript - 给定一个整数数组,找到数组中第二大和第二小的整数

转载 作者:行者123 更新时间:2023-12-01 15:54:29 24 4
gpt4 key购买 nike

我正在尝试想出一个函数,它将接受一个整数数组并输出第二大数字和第二小数字。该函数将考虑 float 、重复数和负数。

两个函数通过了除 test2 之外的所有测试。

var test1 = [7, 7, 12, 98, 106]
answer1 = {2nd Min: 12, 2nd Max: 98}

var test2 = [5, 23, -112, 6, 70, 70, -112]
answer2 = {2nd Min: 5, 2nd Max: 23}

var test3 = [-22, 22]
answer3 = {2nd Min: 22, 2nd Max: -22}

var test4 = [10, 89, 3]
answer = {2nd Min: 10, 2nd Max: 10}

var test5 = [10.4, -12.09, .75, 22]
answer3 = {2nd Min: 0.75, 2nd Max: 10.4}

/*/ \ \
---SOLUTION 1---
\ \ /*/
function secondGreatLow1(arr) {
//make copy of array because it will be spliced in the following functions
var arrCopy = arr.slice();
//push returned values of each function into this the answer array
var answer = []
answer.push(secondMin(arrCopy));
answer.push(secondMax(arrCopy));
return answer;
};

//helper function 1
var secondMin = function (arr){
var arrCopy = arr.slice();
//check length of array
if (arr.length == 2) {
return arr[1];
} else {
var min = Math.min.apply(null, arrCopy);
arrCopy.splice(arrCopy.indexOf(min), 1);
//check for duplicates
for (var i = 0; i < arrCopy.length; i++) {
if (arrCopy.indexOf(min) === -1) {
//.apply is used for arrays
return Math.min.apply(null, arrCopy);
} else {
arrCopy.splice(arrCopy.indexOf(min), 1);
return Math.min.apply(null, arrCopy);
}
};
}
};

//helper function 2
var secondMax = function (arr){
var arrCopy = arr.slice();
if (arr.length == 2) {
return arr[0];
} else {
var max = Math.max.apply(null, arrCopy);
arrCopy.splice(arrCopy.indexOf(max), 1);
//check for duplicates
for (var i = 0; i < arrCopy.length; i++) {
if (arrCopy.indexOf(max) === -1) {
return Math.max.apply(null, arrCopy);
} else {
arrCopy.splice(arrCopy.indexOf(max), 1);
return Math.min.apply(null, arrCopy);
}
};
}
};



/*/ \ \
---SOLUTION 2---
\ \ /*/
function secondGreatLow2 (numbers) {
var arr = withoutDuplicates(numbers);
arr.sort(function(a,b) { return a-b; });
return arr[1] + ' ' + arr[arr.length-2];
};

// helpers
var withoutDuplicates = function(arr) {
var out = [];
for(var i=0; i<arr.length; i++) {
if(i === 0 || arr[i] !== arr[i-1]) {
out.push(arr[i]);
}
}
return out;
};

最佳答案

在您的第二个解决方案中,您的 withoutDuplicates 函数似乎在列表已排序的假设下运行(通过将一个元素与前一个元素进行比较来检查重复项);但是,在 secondGreatLow2 中,您调用 withoutDuplicates 而不执行某种排序。

如果您更改了这两行的顺序,则解决方案 #2 看起来有效假设您没有任何浮点不匹配,即 3.9999999999997 != 3.99999999998

关于javascript - 给定一个整数数组,找到数组中第二大和第二小的整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32340896/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com