題目地址:
https://leetcode.com/problems/counting-elements/
給定一個數組,數一下有多少個數滿足其加一後也存在於數組中。用哈希表存一下即可。代碼如下:
import java.util.HashSet;
import java.util.Set;
public class Solution {
public int countElements(int[] arr) {
Set<Integer> set = new HashSet<>();
for (int n : arr) {
set.add(n);
}
int res = 0;
for (int n : arr) {
res += set.contains(n + 1) ? 1 : 0;
}
return res;
}
}
時空複雜度。