因为 -10^9 <= a[N] <= 10^9 in float,使用堆来避免精度损失。
如果您不知道什么是堆及其操作,您可以在大多数算法书籍和网络上找到它们。
这是伪代码,我想 i,j,m,n 给出:
build a[i...j] to a max-heap heap1;
build a[m...n] to a min-heap heap2;
size1 = j-i+1;
size2 = n-m+1;
while(size1>1) {
n1 = extractmax();
n2 = extractmax();
temp = n1+n2;
insert(heap1,temp)
}
//do the same thing to heap2,but use extractmin() instead of extractmax()
result = abs(a[i])+a[m];
如果没有给出 i,j,m,n,则按分区查找,这是快速排序的典型部分。
例如
a[0] = 0;
i=j=0;//a[0] is useless, and 1 ≤ i ≤ j < m ≤ n ≤ N
m=n=N;
if(a[N]<=0)
temp = a[N];
a[N] = -1;
//pre: a[i...j] is non-positive
a[m...n] is non-negetive
while(j<=m+1){
while(a[j+1]<=0)
j++;
while(a[m-1]>=0)
m--;
if(j+1>m)
break;
swap(a[j+1],a[m-1]);
j++;m--;
}
if(temp<=0) { //insert a[N] back
a[N] = a[m];
a[m] = temp;
j = m;
m++;
}
//then you will have checked all elements
//and make sure that non-positive elements are consecutive
//so as to non-negative elements
//now you have i,j,m,n to run pseudo-code at the beginning.
//although i,j may be not more than 0,it depends on the data in your array.