개인 공부/코딩테스트
[c++][leetcode] Counting Elements :: seoftware
seowit
2020. 4. 7. 20:18

소스코드
class Solution {
public:
int countElements(vector<int>& arr) {
int answer = 0;
unordered_map<int, int> cnt;
for(int i : arr){
cnt[i]++;
}
for(int i = 0; i < 1001; i++){
if(cnt[i] > 0 && cnt[i+1] > 0){
answer += cnt[i];
}
}
return answer;
}
};
unordered_map을 이용하여 arr에 있는 값을 인덱스(i)로 하여 cnt[i] 를 ++해준다.