  GabrielxD

• 累计撰写 667 篇文章
• 累计创建 127 个标签
• 累计收到 15 条评论

### 目 录CONTENT # 【哈希表, 二分查找】算术三元组的数目 2022-08-08 / 0 评论 / 0 点赞 / 183 阅读 / 517 字

## 题目

6136. 算术三元组的数目

• i < j < k
• nums[j] - nums[i] == diff
• nums[k] - nums[j] == diff

输入：nums = [0,1,4,6,7,10], diff = 3

(1, 2, 4) 是算术三元组：7 - 4 == 3 且 4 - 1 == 3 。
(2, 4, 5) 是算术三元组：10 - 7 == 3 且 7 - 4 == 3 。


输入：nums = [4,5,6,7,8,9], diff = 2

(0, 2, 4) 是算术三元组：8 - 6 == 2 且 6 - 4 == 2 。
(1, 3, 5) 是算术三元组：9 - 7 == 2 且 7 - 5 == 2 。


• 3 <= nums.length <= 200
• 0 <= nums[i] <= 200
• 1 <= diff <= 50
• nums 严格 递增

## 解题

### 方法一：哈希表

#### 代码

class Solution {
public int arithmeticTriplets(int[] nums, int diff) {
Set<Integer> set = new HashSet<>(){{
for (int num : nums) this.add(num);
}};
int count = 0;
for (int num : nums) {
if (set.contains(num - diff) && set.contains(num + diff)) count++;
}
return count;
}
}

class Solution {
public:
int arithmeticTriplets(vector<int>& nums, int diff) {
unordered_set<int> st(nums.begin(), nums.end());
int count = 0;
for (int& num : nums) {
if (st.count(num - diff) && st.count(num + diff)) ++count;
}
return count;
}
};


### 方法二：二分查找

#### 代码

class Solution {
public int arithmeticTriplets(int[] nums, int diff) {
int count = 0;
for (int num : nums) {
if (Arrays.binarySearch(nums, num - diff) >= 0 &&
Arrays.binarySearch(nums, num + diff) >= 0) count++;
}
return count;
}
}

class Solution {
public:
int arithmeticTriplets(vector<int>& nums, int diff) {
int count = 0;
for (int& num : nums) {
if (binary_search(nums.begin(), nums.end(), num - diff) &&
binary_search(nums.begin(), nums.end(), num + diff)) count++;
}
return count;
}
};

0