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.
The key idea is to efficiently check for each element x in the array if x + 1 exists in the array. Using a hash set allows for constant time lookups, making the solution efficient even with duplicates.
classSolution {
publicintcountElements(int[] arr) {
Set<Integer> s =new HashSet<>();
for (int x : arr) s.add(x);
int ans = 0;
for (int x : arr) {
if (s.contains(x + 1)) ans++;
}
return ans;
}
}
1
2
3
4
5
6
7
8
9
10
classSolution {
funcountElements(arr: IntArray): Int {
val s = arr.toSet()
var ans = 0for (x in arr) {
if (x + 1in s) ans++ }
return ans
}
}
1
2
3
4
5
6
7
8
classSolution:
defcountElements(self, arr: list[int]) -> int:
s = set(arr)
ans =0for x in arr:
if x +1in s:
ans +=1return ans