Given a sorted array of integers, how can we find a pair of integers that sum to K?
e.g. array = 1,3,5,6,10, K = 6, the answer is 1 and 5.
Time complexity should be minimized.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
You may want to look at this blog post:
http://www.codingatwork.com/2011/07/array-sum/
My approach would be to do a binary search of the list for
K/2, then walk one variablealeft and another variablebright trying to find a solutiona+b=K.The idea would be to start
aat the largest number less than or equal toK/2and startbat the smallest number greater thana. Again, use a binary search to findaand letbbe the next element in the array. Thena+b = K, thenreturn (a,b).a+b < K, then movebto the right one position.a+b > K, then moveato the left one position.Of course, you can skip the binary search and just start
aat the beginning of the array andbat the end of the array, and then doa+b = K, thenreturn (a,b).a+b < K, then moveato the right one position.a+b > K, then movebto the left one position.This is probably faster.