[英]how do i find the mode of an array of integers
在这种情况下,用户输入整数数组,并且返回最频繁的整数。
它经过了3次测试,但无论是第2次还是第3次测试都将失败一次。
function arrayMode(array) { if (array.length === 0) { return null; } var sequence = {}; var maxNo = array[3], maxCount = 3; for (var i = 0; i < array.length; i++) { var Entry = array[i]; if (sequence[Entry] === null) sequence[Entry] = -1; else sequence[Entry]++; if (sequence[Entry] > maxCount) { maxNo = Entry; maxCount = sequence[Entry]; } else if (sequence[Entry] == maxCount) { maxNo += '&' + Entry; maxCount = sequence[Entry - 1]; } return maxNo; } } console.log(arrayMode([1, 3, 3, 3, 1])) // output = 3 console.log(arrayMode([1, 2, 3, 1, 1])) // output = 1 console.log(arrayMode([2, 2, 2, 1])) // output = 2
我认为有几个错误,如果您找到一个以前没有见过的条目,则将该条目的sequence
设置为-1
,为什么不设置1
?
然后将maxNo
初始化为array[3]
并将maxCount
为3
,为什么呢?
这对您有意义吗?
function arrayMode(arr)
{
var mode = null;
var frequencies = [];
var maxFrequency = 0;
for (var i in arr)
{
var value = arr[i];
// if we haven't seen this value before, init its frequency to 0
if (frequencies[value]===undefined) frequencies[value] = 0;
// increase this value's frequency
frequencies[value]++;
// if this value's frequency is bigger than the max we've seen
// so far, this value is now the new mode.
if (frequencies[value] > maxFrequency)
{
maxFrequency = frequencies[value];
mode = value;
}
}
return mode;
}
如果要返回所有 modi,以防出现不止一个具有最大频率数的条目(例如,对于[1,1,2,3,3]
您希望模式为1 & 3
),则可以最后通过一个简单的额外循环来做到这一点。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.