Given an array s of n integers design an algorithm to find out whether there exi
ID: 3637547 • Letter: G
Question
Given an array s of n integers design an algorithm to find out whether there exists a pair of integers in s whose sum is equal to a given integer xExplanation / Answer
for (i in 1..n-2) { j = i // Start where i is. k = n // Start at the end of the array. while (k >= j) { // We got a match! All done. return (A[i], A[j], A[k]) if (A[i] + A[j] + A[k] == 0) // We didn't match. Let's try to get a little closer: // If the sum was too big, decrement k. // If the sum was too small, increment j. (A[i] + A[j] + A[k] > 0) ? k-- : j++ } // When the while-loop finishes, j and k have passed each other and there's // no more useful combinations that we can try with this i. }
Related Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.