2006. 差的绝对值为 K 的数对数目

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
const int N = 110;
int h[N];
class Solution {
public:
int countKDifference(vector<int>& nums, int k) {
memset(h, 0, sizeof h);
int cnt = 0;
for (int i = 0; i < nums.size(); i++) {
int t = nums[i];
if (t - k >= 0) cnt += h[t - k];
if (t + k <= 100) cnt += h[t + k];
h[t]++;
}
return cnt;
}
};