1.对于长度为N的数组A,求子数组的和接近0的子数组,要求时间复杂度为O(NlogN)
思路:
1.申请累积和数组sum[i],定义sum[-1]=0;
2.∑Ak=sum(j)-sum(i-1);
3.对sum数组排序,计算相邻元素差值,其中最小值记为min_1;
4.sum数组中最小值记为min_2
5.return min(min_1,min_2);
实现代码如下:
#include <iostream>
#include <algorithm>
using std::cout;
using std::endl;
using std::min;
using std::abs;
class Solution{
public:
void sum_to_zero(int *array, int len){
int *sum = new int[len];
int i;
int j;
if (sum != NULL){
sum[-1] = 0;
for (i = 0; i < len; ++i){
sum[i] = sum[i - 1] + array[i];
}
//排序操作
int min_1 = sum[0];
for (i = 0; i < len-1; ++i){
for (j = i+1; j < len; ++j){
if (sum[i] < sum[j]){
int temp = sum[i];
sum[i] = sum[j];
sum[j] = temp;
}
}
}
for (i = 0; i < len; ++i){
printf("%d ",sum[i]);
}
printf("\n");
for (i = 0; i < len; ++i){
int dist = sum[i] - sum[i - 1];
if (abs(dist) < abs(min_1)){
min_1 = dist;
}
}
int min_2 = sum[0];
for (i = 0; i < len; ++i){
if (abs(sum[i]) < abs(min_2)){
min_2 = sum[i];
}
}
cout << min(min_1, min_2) << endl;
}
return;
}
};
int main()
{
int obj_array[9] = { -13, 7,-14, 15, -6, 17, 10, -11, -4 };
int len = sizeof(obj_array) / sizeof(int);
Solution p;
p.sum_to_zero(obj_array, len);
system("pause");
return 0;
}
算法中用到了技巧sum[-1]=0;但是由于在Heap上开辟了内存空间,因此如果直接调用delete []sum;会出现堆空间释放错误,这里是个待解决的BUG。