[LeetCode] Counting Elements

1426. Counting Elements

Given an integer array arr, count how many elements x there are, such that x + 1 is also in arr. If there are duplicates in arr, count them separately.

1
2
3
4
5
6
7
8
9
10
11
12
class Solution {
public:
int countElements(vector<int>& arr) {
unordered_map<int, int> freq;
for(auto a : arr) freq[a] += 1;
int res = 0;
for(auto [k,v] : freq) {
if(freq.count(k+1)) res += v;
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2023/07/30/PS/LeetCode/counting-elements/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.