/**
* 一个整数数组,求子数组的和,该和与0最接近。
* 仿照后缀数组的做法,求出所有0到i的子数组和,成为新的数组,对该数组快排,然后再求相邻元素差值最小的。
*
*
*/
public class SubArrayZero {
public static int sumZero(int[] a) throws Exception{
int[] b = new int[a.length];
b[0] = a[0];
for(int i=1; i<a.length; i++){
b[i] = a[i] + b[i-1];
}
QuickSort.sort(b);
int v = Tools.abs(b[0], b[1]);
for(int i=2; i<b.length; i++){
int c = Tools.abs(b[i], b[i-1]);
if(c < v){
v = c;
}
}
return v;
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] a = {7,-2,4,-8,-3,5,-1,9,6};
try {
int i = SubArrayZero.sumZero(a);
System.out.println(i);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
子数组的和与0最接近
最新推荐文章于 2018-12-10 10:41:39 发布