-
Notifications
You must be signed in to change notification settings - Fork 0
/
averagePair.js
30 lines (28 loc) · 992 Bytes
/
averagePair.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
/* Write a function called averagePair. Given a sorted array of integers and a target average,
* determine if there is a pair of values in the array where the average of the pair equals the target average.
* There may be more than one pair that matches the average target.
* Time: O(N)
* Space: O(1)
*/
const calculateAverageOf2Nums = (num1, num2) => {
return num1 + num2 / 2;
}
const averagePair = (array, targetAverage) => {
let leftIndex = 0;
let rightIndex = array.length - 1;
while (leftIndex < rightIndex) {
let average = calculateAverageOf2Nums(array[leftIndex], array[rightIndex]);
if (average === targetAverage) {
return true;
} else if (average < targetAverage) {
leftIndex++
} else {
rightIndex--
}
}
return false;
}
console.log(averagePair([1,2,3],2.5)); // true
console.log(averagePair([1,3,3,5,6,7,10,12,19],8)); // true
console.log(averagePair([-1,0,3,4,5,6], 4.1)); // false
console.log(averagePair([],4)); // false