1.问题
You are given a 0-indexed, strictly increasing integer array nums and a positive integer diff. A triplet (i, j, k) is an arithmetic triplet if the following conditions are met:
i < j < k,
nums[j] - nums[i] == diff, and
nums[k] - nums[j] == diff.
Return the number of unique arithmetic triplets.
Example 1:
Input: nums = [0,1,4,6,7,10], diff = 3
Output: 2
Explanation:
(1, 2, 4) is an arithmetic triplet because both 7 - 4 == 3 and 4 - 1 == 3.
(2, 4, 5) is an arithmetic triplet because both 10 - 7 == 3 and 7 - 4 == 3.
Example 2:
Input: nums = [4,5,6,7,8,9], diff = 2
Output: 2
Explanation:
(0, 2, 4) is an arithmetic triplet because both 8 - 6 == 2 and 6 - 4 == 2.
(1, 3, 5) is an arithmetic triplet because both 9 - 7 == 2 and 7 - 5 == 2.
Constraints:
- 3 <= nums.length <= 200
- 0 <= nums[i] <= 200
- 1 <= diff <= 50
- nums is strictly increasing.
2. 解题思路
方法1:
1.新建一个HashSet为set,通过for循环遍历数组添加到set中
2.for循环遍历,set是否包含nums数组中,元素+diff,元素+2*diff,如果有result加1
3.返回result
方法2:
暴力解法,可以参考
3. 代码
代码1:
class Solution {
public int arithmeticTriplets(int[] nums, int diff) {
int result = 0;
Set<Integer> set = new HashSet<>();//1.新建一个HashSet为set,通过for循环遍历数组添加到set中
for(int n:nums){
set.add(n);
}
for(int s:nums){//2.for循环遍历,set是否包含nums数组元素,元素+diff,元素+2*diff,如果有result加1
if(set.contains(s+diff)&&set.contains(s+2*diff)){
result+=1;
}
}
return result;//3.返回result
}
}
解题思路基本相同
public int arithmeticTriplets(int[] nums, int diff) {
int result = 0;
Set<Integer> set = new HashSet<>();
for (int num : nums) {//for循环遍历,如果set中没有数据,set.add()添加数组元素。如果set中存在num - diff&& num - diff * 2,result+1
if (set.contains(num - diff) && set.contains(num - diff * 2))
result++;
set.add(num);
}
return result;
}
解题思路基本,使用hashmap
class Solution {
public int arithmeticTriplets(int[] nums, int diff) {
int result = 0;
HashMap<Integer, Integer> map = new HashMap<>();
for(int i : nums){//1.新建一个hashmap,通过for循环遍历数组添加到map中,map的key为nums,value为1
map.put(i, map.getOrDefault(i, 0) + 1);
}
for (int num : nums) {//2.for循环遍历,map的key是否包含nums数组元素(元素+diff,元素+2*diff),如果有result加1
if (map.containsKey(num+diff) && map.containsKey(num + diff * 2))
result++;
}
return result;//3.返回result
}
}
代码2:
public int arithmeticTriplets(int[] nums, int diff) {
int count = 0;
for (int i = 0; i < nums.length - 2; i++) {
for (int j = i + 1; j < nums.length - 1; j++) {
for (int k = j + 1; k < nums.length; k++) {
if (nums[j] - nums[i] == diff && nums[k] - nums[j] == diff)
count++;
}
}
}
return count;
}