-
Description:
-
Enter an incremental sorting array and a number S, and search for two numbers in the array. Yes, their sum is exactly S. If there are multiple pairs of numbers and the sum is equal to S, the product of the two numbers is the smallest.
-
Input:
-
Each test case contains two rows: the first row contains an integer n and k, n indicates the number of elements in the array, and k indicates the sum of the two. Where 1 <= n <= 10 ^ 6, k is the second line of int contains n integers, each array is of the int type.
-
Output:
-
For each test case, two numbers are output first. If no value is found, "-1-1" is output"
-
Sample input:
-
6 151 2 4 7 11 15
-
Sample output:
-
4 11
When we see this question, we first think of brute-force solutions, but the N size is 1 million, and the brute-force algorithm may Time Out. Is there an o (n) algorithm?
The data entered in the question increases sequentially, and it is to find two numbers and quickly think of a fast sorting algorithm. Generally, such an ordered number can be referred to by the sorting algorithm (three while loops ):
1 First, we judge array [low] + array [height] <k, so low will always add 1 and ensure low
2 then judge array [low] + array [height]> k, then the height will be reduced by 1 and the low
3 judge segment array [low] + array [height] = k. If it is equal to k, 1 is returned, indicating that 1 is found; otherwise, continue
Haha, isn't it the same idea as QuickShield.
The following code is used:
# Include <stdio. h> # include <stdlib. h> # define MaxSize limit 00int Array [MaxSize]; int findMinTwoNumber (int vK, int vN, int * vLeft, int * vRight) {if (vN <2) return 0; int Low, Hight; Low = 0; Hight = vN-1; while (Low <Hight) {while (Array [Low] + Array [Hight] <vK & Low <Hight) + + Low; while (Array [Low] + Array [Hight]> vK & Low <Hight) -- Hight; if (Array [Low] + Array [Hight] = vK & Low <Hight) {* vLeft = Low; * vRight = Hight; return 1 ;}} return 0 ;}int main () {int K, N, I, Ret, Left, Right; while (scanf ("% d", & N, & K )! = EOF) {for (I = 0; I <N; ++ I) {scanf ("% d", & Array [I]);} Ret = findMinTwoNumber (K, n, & Left, & Right); if (Ret) {printf ("% d \ n", Array [Left], Array [Right]);} else {printf ("-1-1 \ n") ;}// system ("pause"); return 0 ;}Http://blog.csdn.net/xiaoliangsky/article/details/40901373
Http://ac.jobdu.com/problem.php? Pid = 1, 1352
023 and two numbers for S (keep it up)