123 | function binarySearch(arr, x, start, end) {
while (start <= end) {
let mid = Math.floor((start + end) / 2);
if (arr[mid] === x) return mid;
if (arr[mid] < x) start = mid + 1;
else end = mid - 1;
}
return -1;
}
function getTarget(arr, target) {
arr.sort((a, b) => a - b);
for (let i = 0; i < arr.length; i++) {
let compData = target - arr[i];
let foundIndex = binarySearch(arr, compData, i + 1, arr.length - 1);
if (foundIndex !== -1) {
return [arr[i], compData];
}
}
return null;
}
const target = -1;
const arr = [1, 2, 3, 543, 222, 63, 4567, 345, 73, 4587345, 7, 234, 6123, 65, 1346, 134, 76, 2457, 245, 7, 2134, 61, 3467, 134, 7, 347, 134, 7, 13, 7134, 7, 134, 7134, 7, 134, 713, 47, 1];
console.log(getTarget(arr, target));
| ready |
432 | function getTarget(arr, target){
let numMap = new Map();
for (let i = 0; i < arr.length; i++) {
let compData = target - arr[i];
if(numMap.has(compData)){
return[compData, arr[i]]
}
numMap.set(arr[i], i)
}
return null;
}
const target = -1
const arr = [1,2,3,543,222,63,4567,345,73,4587345,7,234,6123,65,1346,134,76,2457,245,7,2134,61,3467,134,7,347,134,7,13,7134,7,134,7134,7,134,713,47,1];
console.log(getTarget(arr, target))
| ready |