-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtwo-sum.js
More file actions
27 lines (25 loc) · 820 Bytes
/
Copy pathtwo-sum.js
File metadata and controls
27 lines (25 loc) · 820 Bytes
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
// given an input array which is sorted, find two elements whose sum is equal to target
//Example: input: arr[] = [-8, 1, 4, 6, 10, 45], target = 16
function findTargetSum(array,target){
if(array.length===0||array.length<2){
return false
}
let leftPointer=0
let rightPointer=array.length-1
while(leftPointer<rightPointer){
const obtainedSum=array[leftPointer]+array[rightPointer]
if(obtainedSum===target){
return {
firstNumber:array[leftPointer],
secondNumber:array[rightPointer]
}
}else if(obtainedSum<target){
leftPointer++
}else if(obtainedSum>target){
rightPointer--
}
}
return false
}
const result=findTargetSum([-8, 1, 4, 6, 10, 45],16)
console.log(result)