The algorithm is described as follows: Quickly find out two numbers in an array, and let the sum of these two numbers equal to a given value. For the moment, I assume that all the integers in the array are unequal. This question I was asked in an interview, for various reasons, I did not answer up, very embarrassed. In fact, this problem is very simple, we use a relatively ingenious method to achieve the next. Note that elements that do not use a two-layer loop are traversed. The sample code is uploaded to: https://github.com/chenyufeng1991/SumTo100.
The algorithm is described as follows:
(0) The original array is sorted first, and becomes the increment array;
(1) on the array header after sorting I [0] and array tails J [N-1] sum to determine whether it is equal to - , equals - print, and then execute ( 3 ), otherwise execute ( 2 );
(2) If the addition is less than - , you i++,j not change. If the sum is greater than , then i will not change,j--; Continue (1);
(3) Array subscript i++ , j-- , continue execution ( 1 );
(4) when i==j , exit the program.
The code is implemented as follows:
main.c//sumto100////Created by Chenyufeng on 16/2/5.//copyright©2016 year chenyufengweb. All rights reserved.//#include <stdio.h>/** * requires finding all combinations of two numbers added to 100 in the array; Let me first assume that the number 22 is not equal; */void findSumTo100 (int *a, int n); int main (int argc, const char * argv[]) {//original array; int a[] = {55,50,99,80,1,30,70}; /** * First sorts the array, the following is the sorted result; */int a_sort[] = {1,30,50,55,70,80,99}; FINDSUMTO100 (a_sort,7); return 0;} /** * The simple algorithm is this: (1) Add to the sorted array header I [0] and the tail J [N-1], determine whether it is equal to 100, equal to 100 to print, then execute (3), otherwise execute (2), (2) If the addition is less than 100, the i++,j is unchanged. If the addition is greater than 100, then I will not change, j--; continue execution (1) (3) array subscript i++,j--, continue execution (1); (4) When I==j, exit the program. */void findSumTo100 (int *a,int n) {for (int i = 0,j = n-1; I! = j;) {int sum = A[i] + a[j]; if (sum = =) {printf ("%d%d\n", a[i],a[j]); i++; j--; } else if (Sum <) {i++; } else if (Sum >) {j--; } }}
Classical algorithm Learning--quickly find two numbers in an array, add equals a specific value