-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathaveragePair.js
42 lines (34 loc) · 983 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
31
32
33
34
35
36
37
38
39
40
41
42
// 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.
// Bonus Constraints:
// Time: O(N)
// Space: O(1)
// Sample Input:
// averagePair([1,2,3],2.5) // true
// averagePair([1,3,3,5,6,7,10,12,19],8) // true
// averagePair([-1,0,3,4,5,6], 4.1) // false
// averagePair([],4) // false
function averagePair(arr, ave){
let sum = ave * 2;
if(arr.length === 0){
return false;
}
arr.sort((a,b) =>a-b);
let left = 0;
let right = arr.length - 1;
while(left < right){
if(arr[left] + arr[right] < sum){
left++;
}
else if(arr[left] + arr[right] > sum){
right--;
}
else{
return true;
}
}
return false;
}
console.log(averagePair([],4))