第四题
一个有序数组a={1,3,6,.....,89,...,90318..}和一个数X,从数组中找出两个数,使得两个数的和等于X,要使时间复杂度尽量的低。
LZ的思路
第一个想法 二分查找,开始自己以为大概是O(NlogN),但是面试官说是O(N²),这个肯定不对;
第二个想法 用bitset,数组有的位置为1,然后循环从第一个数用X减,减出来的值如果置为了1则,则输出,不行下一个。这个是O(N)+O(N) 事件复杂度是O(N),大家有其他办法,自己说哈!
最开始的思路:
// TestSTL.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <iostream>
using namespace std;
#define XValue (94)
#define Len (20)
int _tmain(int argc, _TCHAR* argv[])
{
int MyArray[Len];
memset(MyArray,0,Len);
int k=0;
int j=0;
for (int i=0; i<100 && k<Len;i=i+j)
{
j++;
//cout << i+j << " " << endl;//输出1、3、6、10、15
MyArray[k]=i+j;
cout << MyArray[k] << " " << endl;
k++;
}
int MidValue=XValue/2;
for(int m=0; MyArray[m]<MidValue; m++)
{
for(int n=k-1; MyArray[n]>=MidValue; n--)
{
if (MyArray[m]+MyArray[n]==XValue)
{
cout << MyArray[m] << "+" << MyArray[n] << endl;
}
}
}
system("pause");
return 0;
}
改进思路:变双重循环为单重循环
// TestSTL.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <iostream>
using namespace std;
#define XValue (94)
#define Len (20)
int _tmain(int argc, _TCHAR* argv[])
{
int MyArray[Len];
memset(MyArray,0,Len);
int k=0;
int j=0;
for (int i=0; i<100 && k<Len;i=i+j)
{
j++;
//cout << i+j << " " << endl;//输出1、3、6、10、15
MyArray[k]=i+j;
cout << MyArray[k] << " " << endl;
k++;
}
int m=0;
while (m<k-1)
{
if (MyArray[m]+MyArray[k-1]>XValue)
{
k--;
}
else if (MyArray[m]+MyArray[k-1]<XValue)
{
m++;
}
else
{
cout << MyArray[m] << "+" << MyArray[k-1] << endl;
k--;//或者m++;
}
}
system("pause");
return 0;
}