題目描述
給定一個整數數組arr,計數元素x,使x + 1也在arr。
如果在arr中有重複的,分開計數。
例1:
Input: arr = [1, 2, 3]
Output: 2
例2:
Input: [1, 1, 3, 3, 5, 5, 7, 7]
Output: 0
例3:
Input: [1, 3, 2, 3, 5, 0]
Output: 3
例4:
Input: arr = [1, 1, 2, 2]
Output: 2
思路分析
首先使用字典將數組中的值及其出現的次數按照鍵值對的形式存儲起來,然後遍歷字典對符合要求的元素進行計數。要求掌握字典的遍歷方法。
js代碼
function countingElements(arr) {
let sum = 0;
let m = new Map();
arr.forEach(item => {
if(m.has(item)){
m.set(item, m.get(item) + 1);
}
else{
m.set(item, 1);
}
});
m.forEach((value, key) => {
if(m.has(key + 1)){
sum += value;
}
})
return sum;
}