Task You are given a sorted integer array arr.(任务您将获得一个排序的整数数组arr。)
It contains several unique integers(negative, positive, or zero).(它包含几个唯一的整数(负数,正数或零)。)
Your task is to find the largest d such that a + b + c = d, where a, b, c, and d are distinct elements of arr.(您的任务是找到最大的d,以使a + b + c = d,其中a,b,c和d是arr的不同元素。) If no such an element d found, return null.(如果找不到这样的元素d,则返回null。)
Example:(例:)
For arr = [2,3,5,7,12], the output should be 12 (this array passes my function correctly)(对于arr = [2,3,5,7,12],输出应为12(此数组正确传递了我的函数))
For arr = [-100,-1,0,7,101], the output should be 0 (this one does not pass)(对于arr = [-100,-1,0,7,101],输出应为0(此不通过))
I could manage the positive numbers check but my function miserably fails with negatives(我可以管理正数检查,但是我的功能由于负数而失败)
function findD(arr) {
myArr = arr.sort((a, b) => b - a);
for (var i = 0; i < myArr.length; i++) {
for (var k = i + 1; k < myArr.length - 2; k++) {
var j = k + 1,
d = myArr.length - 1;
while (j < d) {
let sum = myArr[k] + myArr[j] + myArr[d];
if (sum == myArr[i]) {
return myArr[i];
} else if (sum < myArr[i]) {
d--;
} else if (sum > myArr[i]) {
j++;
}
}
}
}
return null
}
how to handle negative values in the array?(如何处理数组中的负值?)
ask by metamorph_online translate from so
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…