美文网首页
返回数组中最大的三个数

返回数组中最大的三个数

作者: 沃尔德 | 来源:发表于2021-08-05 11:18 被阅读0次

// 一

function threeNums(nums, count) {
var result = []
var newList = []
var step = 0
var len = nums.length

var less = len - count
for (var k = 0; k < len; k++) {
var cur = nums[k]
// if ( less <= k) {
if (cur < nums[k - 1]) {
newList[k] = nums[k - 1]
newList[k - 1] = cur
} else {
newList[k] = nums[k]
}
// }
}

return getCountNum(result, newList, count)
}

function getCountNum(result, newList, count) {
if (result.length >= count) {
return result
}
result[result.length] = newList[newList.length - result.length - 1]
return getCountNum(result, newList, count)
}

var arr = [5, 2, 6, 8, 9, 11]
// var arr = [5, 2, 1, 8, 6, 0]
var rts = threeNums(arr, 3)
console.log(rts.toString())

// 二

function threeNums(nums) {
var n1 = 0,
n2 = 0,
n3 = 0
var len = nums.length
for (var i = 0; i < len; i++) {
var cur = nums[i]
if (cur > n1) {
n3 = n2
n2 = n1
n1 = cur
} else if (cur > n2) {
n3 = n2
n2 = cur
} else if (cur > n3) {
n3 = cur
}
}
return [n1, n2, n3]
}

var arr = [5, 2, 6, 8, 9, 11]
var rts = threeNums(arr)
console.log(rts.toString())

// 三


image.png

相关文章

网友评论

      本文标题:返回数组中最大的三个数

      本文链接:https://www.haomeiwen.com/subject/rormvltx.html