erbing / logic-training

logic-training and code-everyday
5 stars 0 forks source link

找出数组中重复项最多的一个数字 #1

Open erbing opened 5 years ago

erbing commented 5 years ago
let arr = [1,2,3,3,3,4,4,5,5,5,5,5,5,6,6,6,6,45,43,3,2,2,3,23]
let getMaxRepeat = (arr) => {
    //  todo
}
erbing commented 5 years ago
const findMax = (arr) => {
    let newObj = {}
    if(!arr.length) return '数组不能为空噢~'
    if (arr.length == 1) return arr[0]
    for (let i = 0; i < arr.length; i++) {
        const e = arr[i];
        if(!newObj[e]) newObj[e] = 0
        newObj[e] = newObj[e] + 1
    }
    let objKeys = Object.keys(newObj)
    let objVaule = Object.values(newObj)
    let maxIndex = objVaule.indexOf(Math.max(...objVaule))
    let maxRepeatValue = objKeys[maxIndex]
    return maxRepeatValue 
}
babyxu51521 commented 5 years ago
let arr = [1,1,2,3,1,2,3,4,5,1,2,1,];
let  removal_arr = Array.from(new Set(arr));   //去重的数组

let count = 0;
let obj = {};   //每个数字出现的次数的统计
removal_arr .forEach(i  => {
   count = 0;
  arr.forEach(j => {
       if (i === j) {
           count++;
         }
     })
    obj[i] = count;
 })
zds15172671314 commented 5 years ago
let arr = [1, 2, 3, 3, 3, 4, 4, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 45, 43, 3, 2, 2, 3, 23]
    let getMaxRepeat = (arr) => {
      let h = {};
      let maxNum = 0;
      let maxEle = null;
      for (let i = 0; i < arr.length; i++) {
        let a = arr[i];
        h[a] === undefined ? h[a] = 1 : (h[a]++);
        if (h[a] > maxNum) {
          maxEle = a;
          maxNum = h[a];
        }
      }
      return '最多得是' + maxEle + '次数为' + maxNum;
    }
erbing commented 5 years ago

@babyxu51521 @zds15172671314 这个代码可以用 markdown 格式,稍微美观一些

Amorcy commented 5 years ago
var arr = [1,2,3,3,3,4,4,5,5,5,5,5,5,6,6,6,6,45,43,3,2,2,3,23]
var getMaxRepeat = (arr) => {
    let hash = {}
    arr.reduce((pre, next)=> {
        hash[next] ? hash[next]++ : hash[next] = 1
    })
    let value = Object.values(hash)
    let key  = Object.keys(hash)
    let idx = value.indexOf(Math.max(...value))
    let maxRepeatValue = key[idx]
    console.log(maxRepeatValue)
    return maxRepeatValue
}
getMaxRepeat(arr)