题目:有N个正实数(注意是实数,大小升序排列) x1 , x2 ... xN,另有一个实数M。 需要选出若干个x,使这几个x的和与 M 最接近。 请描述实现算法,并指出算法复杂度。
代码如下:
#include<iostream>
using namespace std;
int min_diff(int data[],int n,int &min_i,int &min_j,int number);
int main()
{
int number,n,i;
cin>>number>>n;
int *data=new int[n];
for(i=0;i<n;i++)
cin>>data[i];
int min_i,min_j;
int min_d=min_diff(data,n,min_i,min_j,number);
int sum=0;
for(i=min_i;i<min_j;i++)
{
sum=sum+data[i];
cout<<data[i]<<" + ";
}
sum=sum+data[i];
cout<<data[i]<<" = "<<sum<<endl;
cout<<"The min difference with "<<number<<" is "<<min_d<<endl;
delete []data;
return 0;
}
int min_diff(int data[],int n,int &min_i,int &min_j,int number)
{
if(data==NULL||n<=0)
return 0;
int i=0,j=0;
min_i=i;
min_j=j;
int min_d=0x7fffffff;
int sum=data[0];
while(i<=j&&j<n)
{
if(sum==number)
{
min_i=i;
min_j=j;
min_d=0;
break;
}
else if(sum>number)
{
if(sum-number<min_d)
{
min_d=sum-number;
min_i=i;
min_j=j;
}
sum=sum-data[i];
i++;
}
else
{
if(number-sum<min_d)
{
min_d=number-sum;
min_i=i;
min_j=j;
}
j++;
sum=sum+data[j];
}
}
return min_d;
}
时间复杂度度为O(n),空间复杂度为O(1).