內容:尋找衆數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>
上述代碼爲閒時所構,還有優化空間。下回分享效率更高的分志法求衆數。