您的位置:首页 > 其它

给定一个数组,求x和y,使得abs(x+y)最接近零

2012-11-30 22:06 295 查看
// 给定一个数组,求x和y,使得abs(x+y)最接近零
// 要求时间复杂度尽量小
// 先排序:

#include<stdio.h>
#include <algorithm>
#include <iostream>

using namespace std;
void getZeroPoint(int *p, int n, int&a,int &b)
{

if (p[0] <=0 && p[n-1]<=0)
{
cout<<"非正数组"<<endl;
a=p[n-2];
b=p[n-1];
return;
}
if (p[0]>=0 && p[n-1]>=0)
{
cout<<"非负数组"<<endl;
a=p[0];
b=p[1];
return;
}
//////////////////////////////////////////////////////////////////////////
int i=0, j=n-1;
int sum=RAND_MAX;
while (i<j)
{
cout<<"i: "<<i<<"     j: "<<j;
if (p[i]+p[j]==0)
{
a=p[i];
b=p[j];
return;
}
if (abs(p[i]+p[j])<sum)
{
a=p[i];
b=p[j];
sum = abs(p[i]+p[j]);
}
cout<<"     "<<sum<<endl;
if (abs(p[i]) > abs(p[j]))
{
i++;
}
else
{
j--;
}
}
}

int main()
{
int p[10]={-5,3,1,11,-6,2,-20,67,8,9};
//int p[10]={-5,-3,-1,-11,-6,-2,-20,-67,-8,-9};
cout<<"原始数组:"<<endl;
copy(p,p+10,ostream_iterator<int>(cout," "));
cout<<endl;

cout<<"排序后的数组:"<<endl;
sort(p,p+10);
copy(p,p+10,ostream_iterator<int>(cout," "));
cout<<endl;

cout<<endl<<"开始操作:"<<endl<<"下标1    下标2     和"<<endl;
int a,b;
getZeroPoint(p,  10, a,b);
cout<<"result:  "<<a<<" "<<b<<endl;

return 0;
}


结果:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐