在排序过的数组查找两个数,使得它们的和正好是输入的那个数字

本文介绍了一种在已排序数组中寻找两个数使其和为特定值的有效算法,该算法的时间复杂度为O(n)。此外,还讨论了如何扩展此算法以解决三数之和的问题。
第14题(数组):
题目:输入一个已经按升序排序过的数组和一个数字,
在数组中查找两个数,使得它们的和正好是输入的那个数字。
要求时间复杂度是O(n)。如果有多对数字的和等于输入的数字,输出任意一对即可。
例如输入数组1、2、4、7、11、15和数字15。由于4+11=15,因此输出4和11。




//coder:LEE
//20120309
#include<iostream>
#include<cassert>
using namespace std;
void FindNumbers(int *A,int length,int expectedNumber)
{
assert(A!=NULL&&length>0);
int *pAhead=A;
int *pBehind=A+length-1;
while(pAhead<pBehind)
{
while(*pAhead+*pBehind>=expectedNumber)
--pBehind;
while(*pAhead+*pBehind<expectedNumber)
++pAhead;
if(*pAhead+*pBehind==expectedNumber)
cout<<*pAhead<<" "<<*pBehind<<endl;
}
}


int main()
{
    int A[]={1,2,4,6,7,9,11,15};
FindNumbers(A,sizeof(A)/sizeof(int),15);
return 0;
}


没按要求来!下次参考http://zhedahht.blog.163.com/blog/static/2541117420072143251809/改进下。
bool FindTwoNumbersWithSum
(
      int data[],           // a sorted array
      unsigned int length,  // the length of the sorted array     
      int sum,              // the sum
      int& num1,            // the first number, output
      int& num2             // the second number, output

)


扩展(1):输入一个数组,判断这个数组中是不是存在三个数字i, j, k,满足i+j+k等于0。
思路:先排序,然后遍历数组中每个数字k,利用上面的方法寻找除当前数字外数组中和为-k的两个数。

代码下次补上。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值