JS尋找眾數(easy)
阿新 • • 發佈:2019-02-03
內容:尋找眾數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>