求数组平衡点
public class Balence {
public int getBalance(int[] array) {
int index = -1;
int lsum = 0, rsum = 0;
for (int i = 0; i < array.length; i++) {
rsum += array[i];
}
int j = 0;
while (j < array.length - 1) {
lsum += array[j];
rsum -= array[j + 1];
if (lsum != rsum) {
break;
}
j++;
}
if (lsum == rsum) {
index = lsum;
} else {
System.out.println("no balence index");
}
return index;
}
public static void main(String[] args) {
int[] array = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
Balence bl = new Balence();
int balance_index = bl.getBalance(array);
if (balance_index != -1) {
System.out.println("balence_index=" + balance_index);
}
}
}