我如何找到整数数组的模式

时间:2019-07-01 22:32:47

标签: javascript arrays

在这种情况下,用户输入整数数组,并且返回最频繁的整数。

它经过了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

1 个答案:

答案 0 :(得分:0)

我认为有几个错误,如果您发现以前没有看到的条目,则将该条目的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;
}

如果您要返回 all modi,以防出现多个条目且具有最大频率(例如,对于[1,1,2,3,3],您希望模式为{{1 }}),那么您可以在最后通过一个简单的额外循环来实现。