📅  最后修改于: 2023-12-03 14:49:24.533000             🧑  作者: Mango
这是一个用于计算排序数组中的三元组的算法。该算法的输入是一个已排序的数组,要求计算出数组中所有差异等于给定差值 D 的三元组。三元组是由相邻的三个元素组成,且它们之间的差异等于给定的 D。
def findTriplets(nums, D):
result = []
for i in range(1, len(nums)):
target1 = nums[i] - D
target2 = nums[i] + D
if binarySearch(nums, target1) and binarySearch(nums, target2):
result.append((nums[i] - D, nums[i], nums[i] + D))
return result
def binarySearch(nums, target):
left = 0
right = len(nums) - 1
while left <= right:
mid = (left + right) // 2
if nums[mid] == target:
return True
if nums[mid] < target:
left = mid + 1
else:
right = mid - 1
return False