1 /* 2 一个N个整数的无序数组,给你一个数sum,求出数组中是否存在两个数,使他们的和为sum O(nlogn) 3 解题思路:先排序 在左右夹击判断,类似二分查找的思想。 4 */ 5 #include <stdio.h> 6 #include <stdlib.h> 7 int find(int a[], int len, int sum, int *x, int *y) 8 { 9 10 int i = 0, j = len - 1; 11 12 if (sum < a[0]) { 13 return -1; 14 } 15 16 while (i != j) { 17 if (a[i] + a[j] == sum) { 18 *x = a[i]; *y = a[j]; 19 return 0; 20 } 21 else if (a[i] + a[j] > sum) { 22 j--; 23 } 24 else { 25 i++; 26 } 27 28 } 29 30 return -1; 31 } 32 33 int cmp(const void *a,const void *b) 34 { 35 return (int *)a - (int *)b; 36 } 37 38 int main() 39 { 40 int a[] = {1,3,5,7,9,11,25,26,30,35,50}; 41 int sum = 32, x = 0, y = 0; 42 qsort(a,sizeof(a)/sizeof(a[0]),sizeof(a[0]),cmp); 43 for(sum = 0; sum < 86; sum++) 44 { 45 if (-1 != find(a, sizeof(a) / sizeof(a[0]), sum, &x, &y)) { 46 printf("find: sum=%d, (%d, %d)\n", sum, x, y); 47 } 48 else { 49 printf("Not find!\n"); 50 } 51 } 52 return 0; 53 }