标签:复杂度 numbers 题目 mic clu stdio.h with 排序 while
本文地址: 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
标签:复杂度 numbers 题目 mic clu stdio.h with 排序 while
原文地址:http://www.cnblogs.com/cxchanpin/p/6790530.html