我们需要编写一个JavaScript函数,该函数接受一个排序的整数数组和一个目标平均值作为第一个和第二个参数。
函数应确定数组中是否存在一对值的平均值,该对值等于目标平均值。
有一个具有O(1)额外空间复杂度和O(n)时间复杂度的解决方案。由于对数组进行了排序,因此有两个索引是有意义的:一个索引从数组的开始到结束(例如y),另一个从数组的结束到开始(例如x)。
为此的代码将是-
const arr = [1, 2, 4, 6, 7, 9, 11];
const averagePair = (arr = [], target = 1) => {
let x = arr.length − 1;
for (let y = 0; y < x; y++) {
while (y < x && arr[x] + arr[y] > 2*target) {
x−−;
};
if (x !== y && arr[x] + arr[y] === 2 * target) {
return true;
};
};
return false;
};
console.log(averagePair(arr, 6.5));输出结果
控制台中的输出将是-
true