给定排好序的数字,求和为某数的两个数字组合。
#include <stdio.h> struct Pair{ int f; int s; } ; int find(int num[], int n, int x, struct Pair pairs[]){ int i = 0; int j = n - 1; int m = 0; for(; i < j; ){ if(num[i] + num[j] < x) i++; else if(num[i] + num[j] > x) j--; else{ pairs[m].f = num[i]; pairs[m].s = num[j]; i++; j--; m++; } } return m; } main(){ int i; struct Pair pairs[10]; int num[] = {1, 2, 3, 4, 5, 6, 7, 8}; int n = 8; int x = 9; int m; m = find(num, n, x, pairs); for(i = 0; i < m; i++) printf("%d %d\n", pairs[i].f, pairs[i].s); }