重新开启每日算法!!!!奥里给,新年新气象!!!
代码实现:
class Solution {
public:
int arithmeticTriplets(vector<int>& nums, int diff) {
int len = nums.size(), ans = 0;
for (int i = 0; i < len; ++i) {
bool flag = find(i, diff, nums);
if (flag) ++ans;
}
return ans;
}
// 查找并判断以nums[i]为左端点,diff为差值是否能形成三元组
bool find(int i, int diff, vector<int>& nums) {
int R = nums.size() - 1, L = i + 1, tar1 = nums[i] + diff, tar2 = tar1 + diff;
return findBinary(nums, L, R, tar1) && findBinary(nums, L, R, tar2);
}
// 二分查找tar
bool findBinary(vector<int>& nums, int L, int R, int tar) {
int lef = L, rig = R;
while(lef <= rig) {
int mid = (lef + rig) / 2;
if (tar < nums[mid]) {
rig = mid - 1;
}else if (tar > nums[mid]) {
lef = mid + 1;
}else {
return true;
}
}
return false;
}
};
解题思路:
遍历所有的nums中的元素,并以其为左端点,判断是否存在另外两个数满足三元组条件。
具体的判断逻辑就是(i, j, k)
n
u
m
s
[
k
]
−
n
u
m
s
[
j
]
=
n
u
m
s
[
j
]
−
n
u
m
s
[
i
]
=
d
i
f
f
nums[k] - nums[j] = nums[j] -nums[i] = diff
nums[k]−nums[j]=nums[j]−nums[i]=diff
为了寻找
n
u
m
s
[
k
]
nums[k]
nums[k]和
n
u
m
s
[
j
]
nums[j]
nums[j],我们可以使用二分查找