JS寻找众数(easy)

内容:寻找众数easy版

关键点:找出数组中出现次数最多的数字

基本实现逻辑:

1、双重循环遍历数组的值,并依次记录每个数在数组中总共出现的次数,并将总次数按顺序插入至新的数组中。

2、通过找出数组中的最大值,即可获得最大值的索引值

3、最终通过索引取得数组中的众数。

强制约定:

 1、下列数组是通过随机生成,可能一个数组中的众数不止一个,下列做法按取最靠前的一位作为众数。

2、当然,如果强制约定1的做法不合理,也可将最大值进行遍历,即可获得最大值索引组成的数组。这样也能找到多个众数。

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>寻找众数</title>
</head>

<body>
</body>
<script>
  function getRandom() {
    return parseInt(Math.random(10) * 10);
  }
  var time1 = new Date().getTime();
  var arr = [];
  for (var i = 0; i < 10000; i++) {
    arr.push(getRandom())
  }
  console.log(arr);
  var resulteArr = [];
  arr.forEach(item => {
    var count = 0;
    arr.forEach(hash => {
      if (item === hash) {
        count++;
      }
    });
    resulteArr.push(count);
  })
  var max = Math.max.apply(null, resulteArr);
  var index = resulteArr.findIndex(item => item === max);
  console.log('众数是:' + arr[index]);
  var time2 = new Date().getTime();
  console.log('总耗时:' + (time2 - time1) + 'ms');
</script>

</html>
上述代码为闲时所构,还有优化空间。下回分享效率更高的分志法求众数。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章