Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
388 views
in Technique[技术] by (71.8m points)

javascript - 查找结果为其他3个数组元素之和的数组元素,d = a + b + c(Find array element which results as a sum of other 3 array elements, d = a + b + c)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This is a known logic problem, there are plenty of efficient algorithms here: https://www.geeksforgeeks.org/find-largest-d-in-array-such-that-abcd/(这是一个已知的逻辑问题,这里有很多有效的算法: https : //www.geeksforgeeks.org/find-largest-d-in-array-such-that-abcd/)

You will just need to write it in javascript (you can get the logic from java/c++/python)(您只需要用javascript编写即可(您可以从java / c ++ / python获取逻辑))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...