第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
题目:输入一个已经按升序排序过的数组和一个数字,
在数组中查找两个数,使得它们的和正好是输入的那个数字。
要求时间复杂度是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的两个数。
代码下次补上。
本文介绍了一种在已排序数组中寻找两个数使其和为特定值的有效算法,该算法的时间复杂度为O(n)。此外,还讨论了如何扩展此算法以解决三数之和的问题。

2526

被折叠的 条评论
为什么被折叠?



