문제


풀이
class Solution {
public int countElements(int[] arr) {
Map<Integer, Integer> map = new HashMap<>();
int count = 0;
for(int n : arr) {
map.put(n,map.getOrDefault(n,0)+1);
}
for (int n : arr) {
if(map.getOrDefault(n + 1, 0) > 0) {
count++;
map.put(n+1, map.get(n+1)-1);
}
}
return count;
}
}
- 배열을 돌면서 해당 원소 (x+1)이 있는지를 찾아야하는 문제
- 원소가 포함되어있는지를 판단할 때는 Hash 기반의 Set이나 Map을 사용하면 O(1)
- there are duplicates in
arr, count them separately 이므로, 중복을 허용하거나 원소의 개수를 세어야함 -> Set보단 Map을 사용!
- arr의 원소를 map에 넣고, 카운팅도 해야하므로 map.getOrDefault() 사용해서 현재 개수에서 +1
- 돌면서 n+1키의 값이 0보다 크다면, arr에 x+1이 존재하는 것이므로 count++하고 값을 -1
- n+1이 항상 arr에 존재하는 것은 아니므로, null을 방지하기 위해 getOrDefault 사용