此时该功能确实返回第二大数字,但我不确定为什么它不适用于负数?
function findSecondLargeNumber(arr) {
var firstLargeNum = 0,
secondLargeNum = 0;
for (var i = 0; i < arr.length; i++) {
if (firstLargeNum < arr[i]) {
secondLargeNum = firstLargeNum;
firstLargeNum = arr[i];
} else if (secondLargeNum < arr[i]) {
secondLargeNum = arr[i];
}
}
return secondLargeNum;
}
console.log(findSecondLargeNumber([1, 4, 5, 6])) //returns 5
console.log(findSecondLargeNumber([-1, -2])) //returns 0 not -1
答案 0 :(得分:1)
这个怎么样:
function findSecondLargeNumber(arr) {
return arr.sort(function(a, b) {
return a - b
})[arr.length - 2];
}
console.log(findSecondLargeNumber([-5,-3,-2,3,6,2])) //returns 3
答案 1 :(得分:1)
在testval上添加math.abs,你很好
function findSecondLargeNumber(arr){
var firstLargeNum = 0,
secondLargeNum = 0;
for(var i=0; i<arr.length; i++){
var testVal = Math.abs(arr[i]);
if(firstLargeNum < testVal) {
secondLargeNum = firstLargeNum;
firstLargeNum = arr[i];
} else if(secondLargeNum < testVal){
secondLargeNum = arr[i];
}
}
return secondLargeNum;
}
console.log(findSecondLargeNumber([1, 4, 5, 6]))
console.log(findSecondLargeNumber([-1, -2]))
答案 2 :(得分:1)
试试这个解决方案:
function findSecondLargeNumber(arr){
const sortedArray = arr.sort((v1, v2)=> v2 - v1);
return sortedArray[1];
}
答案 3 :(得分:1)
干净的代码尝试(尽管它会重新排列数组元素)
arr.sort((e,f) => (f-e))[1]
对于在博物馆展出作为文物的浏览器
arr.sort(function(a,b){return b-a})[1];
答案 4 :(得分:0)
function getSecondLargest(nums) {
// Complete the function
var a = nums.sort(function (a, b) {
return a - b
});
var max = Math.max(...nums);
var rev = a.reverse();
if (nums.length == 1) {
return nums[0];
} else {
for (var i = 0; i < nums.length; i++) {
if (rev[i] < max) {
return rev[i];
} else {
if (nums.length - 1 == i) {
return rev[i];
}
}
}
}
}
var nums = [10, 9, 9, 8, 8, 11, 8, 0, 9, 1];
console.log(getSecondLargest(nums));