本文地址: http://blog.csdn.net/caroline_wendy
题目: 输入一个递增排序的数组和一个数字s, 在数组中查找两个数, 使得它们的和正好是s.
如果有多对数字的和等于s, 输出任意一对即可.
排序数组, 则可以从两端(即最大值, 最小值)开始进行查找, 当和大于时, 则减少前端, 当和小于时, 则递增尾端.
时间复杂度O(n).
代码:
/* * main.cpp * * Created on: 2014.6.12 * Author: Spike */ /*eclipse cdt, gcc 4.8.1*/ #include <stdio.h> #include <stdlib.h> #include <string.h> bool FindNumbersWithSum(int data[], int length, int sum, int* num1, int* num2) { bool found = false; if (length<1 || num1==NULL || num2 == NULL) return found; int ahead = length-1; int behind = 0; while (ahead > behind) { long curSum = data[ahead] + data[behind]; if (curSum == sum) { *num1 = data[behind]; *num2 = data[ahead]; found = true; break; } else if (curSum < sum) ++behind; else --ahead; } return found; } int main(void) { int data[] = {1, 2, 4, 7, 11, 15}; int num1, num2; if (!FindNumbersWithSum(data, 6, 15, &num1, &num2)) printf("Error\n"); printf("num1 = %d num2 = %d\n", num1, num2); }
num1 = 4 num2 = 11
编程算法 - 和为s的两个数字 代码(C),布布扣,bubuko.com
原文地址:http://blog.csdn.net/caroline_wendy/article/details/37689433