存在重复元素
哈希+计数类型
只出现一次
我们遍历数组时,经过数组中的每一项就往map中添加,比如[1,2,3,1]
第一项:遍历到第一个1时,对象返回{ 1: 1 },代表1出现1次
第二项:遍历到2时,返回 { 1: 1, 2: 1 }
第三项:遍历到3时,返回 { 1: 1, 2: 1, 3: 1 }
第四项:遍历到第二个1时,发现原来的对象里已经有1了,返回false
const containsDuplicate = function(nums) {
let map = new Map();
for(let i of nums){
if(map.has(i)){
return true;
}else{
map.set(i, 1);
}
}
return false;
};
只出现一次
const countMap = {};
数组.forEach((item)=> { countMap[item] ? countMap[item] += 1 : countMap[item] = 1 } )
最后再遍历一次countMap,然后看谁的次数是`1`