一个有序数组中找出两个数,使得两个数的和等于X的C++实现源代码

第四题

一个有序数组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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值