// 给定一个数组,求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;
}
结果:

本文介绍了一种算法,该算法通过双指针技术在一个已排序的整数数组中找到两个数,使得它们的和最接近零。文章提供了一个具体的C++实现案例,并展示了从数组初始化到排序再到寻找最优解的全过程。
1467

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



