描述:一个数组,前半部分之和和后半部分之和正好相等,找出中间的索引值。
You are given an array of numbers.
Find out the array index or position where sum of numbers preceding the index is equals to sum of numbers succeeding the index.
输出:
Starting from index 0, adding numbers till index 2 and adding rest of the numbers can be equal
代码部分:
package test;
import java.util.ArrayList;
/*
* You are given an array of numbers.
* Find out the array index or position where sum of numbers
* preceding the index is equals to sum of numbers succeeding the index.
*/
/*
* Example: Array: 2, 4, 4, 5, 4 ,1
* 2 + 4 + 4 = 5 + 4 + 1
* Means: from Index 0 to Index 2 where sum is equals to the following's summation.
*/
public class FindMiddleIndex {
public static void main(String[] args) throws Exception {
ArrayList<Integer> numberArrayList = new ArrayList<Integer>();
numberArrayList.add(1);
numberArrayList.add(8);
numberArrayList.add(3);
numberArrayList.add(3);
numberArrayList.add(3);
FindMiddleIndex findIndex = new FindMiddleIndex();
int middle = findIndex.findMiddlePosition(numberArrayList);
System.out.println("From Index 0 to Index " + middle + " and adding rest of the numbers can be equal");
}
public int findMiddlePosition(ArrayList<Integer> numberList) throws Exception {
int lastIndex = numberList.size() - 1, firstIndex = 0;
int sumLeft = 0;
int sumRight = 0;
while (true) {
if (sumLeft < sumRight) {
sumLeft += numberList.get(firstIndex++);
} else {
sumRight += numberList.get(lastIndex--);
}
if (firstIndex > lastIndex) {
if (sumLeft == sumRight) {
break;
} else {
throw new Exception("Enter a proper number list!!!");
}
}
}
return lastIndex;
}
}
要点:
1. 定义两个指针,一个指向开头,一个指向结尾。
2. 用控制语句,对前半部分的相加和后半部分相加。
3. 找到最终的结果。