// face questions 57 (a): s, and two numbers // Title: Enter a sorted array and incrementing a number s, find the two numbers in the array, such that they // and exactly s. If a plurality of numbers and equal to s, the output can be any pair. #include <cstdio> bool FindNumbersWithSum(int data[], int length, int sum, int* num1, int* num2) { bool found = false; if (length < 1 || num1 == nullptr || num2 == nullptr) return found; int ahead = 0; int behind = length - 1; while (ahead <= behind) { long long result = data[ahead] + data[behind]; if (result == sum) { *num1 = data[ahead]; *num2 = data[behind]; found = true; break; } else if (result > sum) --behind; else ++ahead; } return found; }
// ==================== test code ==================== void the Test ( const char * TestName, int Data [], int length, int SUM, BOOL expectedReturn) { if (testName != nullptr) printf("%s begins: ", testName); int num1, num2; int result = FindNumbersWithSum(data, length, sum, &num1, &num2); if (result == expectedReturn) { if (result) { if (num1 + num2 == sum) printf("Passed. \n"); else printf("FAILED. \n"); } else printf("Passed. \n"); } else printf("FAILED. \n"); } // present and s is the number two, the two numbers in the middle of the array void Test1 () { int data[] = { 1, 2, 4, 7, 11, 15 }; Test("Test1", data, sizeof(data) / sizeof(int), 15, true); } // present and s is the number two, these two figures located two arrays void Test2 () { int data[] = { 1, 2, 4, 7, 11, 16 }; Test("Test2", data, sizeof(data) / sizeof(int), 17, true); } // absent and s is the number of two void the Test3 () { int data[] = { 1, 2, 4, 7, 11, 16 }; Test("Test3", data, sizeof(data) / sizeof(int), 10, false); } // robustness tests void Test4 () { Test("Test4", nullptr, 0, 0, false); } int main(int argc, char* argv[]) { Test1(); Test2 (); Test3 (); Test4 (); return 0; }
Analysis: The book ahead and behind written backwards.
The first set of numbers encountered, i.e. the maximum difference between the outermost two numbers, the product must be minimized.
class Solution { public: vector<int> FindNumbersWithSum(vector<int> array,int sum) { int length = array.size(); int ahead = 0; int behind = length - 1; vector<int> num; while (ahead < behind) { int curSum = array[ahead] + array[behind]; if (curSum == sum) { num.push_back(array[ahead]); num.push_back(array[behind]); break; } else if (curSum > sum) --behind; else ++ahead; } return num; } };