Given an integer array
If there’re duplicates in
Example 1:
Example 2:
Example 3:
Example 4:
Constraints:
1 <= arr.length <= 1000 0 <= arr[i] <= 1000
Solution
We can use HashSet to do fast lookup for all
Code
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
import java.util.HashSet; import java.util.Set; public class CountingElements { public int countElements(int[] arr) { Set<Integer> set = new HashSet<Integer>(); for (int a : arr) { set.add(a); } int cnt = 0; for (int a : arr) { if (set.contains(a + 1)) cnt++; } return cnt; } public static void main(String[] args) { int [] a= {1,2,3}; System.out.println(new CountingElements().countElements(a)); } } |
Output
We encourage you to write a comment if you have a better solution or having any doubt on the above topic.