从数组中任意取出2个数,判断他们的和是否为输入的数字sum,时间复杂度为0(n^2),空间复杂度0(1)
从数组中任意取出2个数,判断他们的和是否为输入的数字sum,时间复杂度为0(n^2),空间复杂度0(1)
假设数据已经是排序好的
#include <stdio.h> #include <stdlib.h> #include <iostream> using namespace std; int a[] = {1,2,3,4,5,6,7,8,9,10}; int size = sizeof(a) / sizeof(int); void twoSum(int data[], unsigned int length, int sum) { int begin = 0; int end = length - 1; int currentSum = data[begin] + data[end]; //假设已经排序好了 while (begin < end) { if (currentSum == sum) { printf("%d\n,%d", data[begin] + data[end]); break; } else { if (currentSum < sum) { begin++; } else { end--; } } } }