微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

JavaScript 映射中出现最高值的键?

如何解决JavaScript 映射中出现最高值的键?

给定一个 (key,value) 对的 JavaScript ma​​p。 找到最高频率“值”的“键”(比如 x )。 鉴于地图中值 (x) 的频率必须大于地图大小的 50%。

var m = new Map;
m.set('0',null);
m.set('1','a');
m.set('2','a');
m.set('3','a');
m.set('4','b');
m.set('5','a');
m.set('6',null);

这里的答案可以是 1、2、3 或 5,因为 a 的频率为 4,大​​于 50地图大小的百分比7


var m = new Map;
m.set('0','b');
m.set('6',null);

这里的答案是 -1,因为 a 的频率为 3,等于地图 6 大小的 50%


[注意]:如果存在多个答案,例如1、或 2、或 3、或 5,随机选择其中之一。


我的算法:
创建原始地图值的频率图说 freqMap.
在 freqMap 中找到具有最大值的键(比如 x)。
检查天气 x 的值大于原始地图大小的 50%。
在原始映射中查找所有值为 x 的键。
通过随机随机选择其中任何一个

解决方法

使用现有的地图 m,我将创建另一个具有以下结构的地图(例如 1):

{
  null: { key: '0',count: 2 },a: { key: '1',count: 4 },b: { key: '4',count: 1 },}

然后我可以找到具有最高值的键。答案不会是随机的,它会是第一个。

var m = new Map();
m.set('0',null);
m.set('1','a');
m.set('2','a');
m.set('3','a');
m.set('4','b');
m.set('5','a');
m.set('6',null);

const freq = new Map();
for (let item of m) {
  const [key,val] = item;
  if (freq.has(val)) {
    const temp = freq.get(val);
    freq.set(val,{...temp,count: temp.count + 1})
  }else {
    freq.set(val,{key: key,count: 1})
  }
}

let maxVal = 0;
let maxKey;
for (let item of freq) {
  const [key,val] = item;
  if (val.count > maxVal) {
    maxVal = val.count;
    maxKey = val.key;
  }
}

if (maxVal > m.size * 0.5) {
  console.log(maxKey)
}else {
  console.log(-1)
}

,

var m = new Map;
m.set('0','b');
m.set('6',null);

const getHighestOccuringKey = (map) => {
//Create a new object with frequency/count along with the keys
  const obj = {}
  for (let [key,value] of map.entries()) {
    if(obj[value]) {
    //if the value is already present,push the new key to the keys and increment the count
      obj[value] = {keys: [...obj[value].keys,key],count: obj[value]?.count + 1}
    } else {
    //else create a new object with value as key and add keys array along with the count
      obj[value] = {keys: [key],count: 1}
    }
  }

//Sort based on the count
  const sortedArr = Object.values(obj).sort((a,b) => b.count - a.count);
  
  //Check if the freq/count is more than 50%
  //If so,return a random key
  if(sortedArr[0].count > m.size/2){
    const len = sortedArr[0].keys.length;
    const index = Math.floor(len * Math.random());
    return sortedArr[0].keys[index];
  } 
  //else return -1
  return -1;
}

console.log(getHighestOccuringKey(m));

m.set('7','a');
console.log(getHighestOccuringKey(m));

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。