要求时间复杂度是O(n)。如果有多对数字的和等于输入的数字M,输出任意一对即可。
例如输入数组1、2、4、7、11、15和数字15。由于4+11=15,因此输出4和11。
思路:
(1)让指针指向数组的头部和尾部,相加,如果小于M,则增大头指针,如果大于则减小尾
指针
(2)退出的条件,相等或者头部=尾部
算法:
void function(int a[],int n,int M){
int i=0,j=n-1;
while(i!=j){
if(a[i]+a[j]==M){
printf("%d,%d",a[i],a[j]);
break;
}
a[i]+a[j]>M?j--:i++;
}
}
完整程序
using System;
namespace ConsoleApp
{
class RunClass
{
static void Main()
{
int[] array = { 1, 2, 3, 5, 6, 7, 9, 10, 12, 13 };
new Helper().Print(array,11);
Console.ReadLine();
}
}
class Helper
{
public void Print(int[] array, int number)
{
if (array.Length == 0 || array == null)
return;
int lowIndex = 0;
int highIndex = array.Length-1;
while (lowIndex < highIndex)
{
if (array[lowIndex] + array[highIndex] < number)
{
lowIndex++;
}
else if (array[lowIndex] + array[highIndex] > number)
{
highIndex--;
}
else
{
Console.WriteLine("{0} {1}", array[lowIndex], array[highIndex]);
lowIndex++;
highIndex--;
}
}
}
}
}