题目描述:一贫如洗的樵夫阿里巴巴在去砍柴的路上,无意中发现了
黄金宝箱满足排在它之前的所有箱子数字和等于排在它之后的所有箱
请帮阿里巴巴找到黄金宝箱,输出第一个满足条件的黄金宝箱编号,
输入描述:
箱子上贴的数字列表,使用逗号分隔,例如1,-1,0。
宝箱的数量不小于1个,不超过10000
宝箱上贴的数值范围不低于-1000,不超过1000
输出描述:
第一个黄金宝箱的编号
补充说明:
示例1
输入:
2,5,-1,8,6
输出:
3
说明:
下标3之前的数字和为:2 + 5 + -1 = 6
下标3之后的数字和为:6 = 6
示例2
输入:
8,9
输出:
-1
说明:
不存在符合要求的位置
示例3
输入:
11
输出:
0
说明:
下标0之前的数字和为:0
下标0之后的数字和为:0
public class 阿里巴巴找黄金宝箱 {
public static int findGoldBox(int[] boxes) {
int totalSum = 0;
for (int box : boxes) {
totalSum += box;
}
int leftSum = 0;
for (int i = 0; i < boxes.length; i++) {
totalSum -= boxes[i];
if (leftSum == totalSum) {
return i;
}
leftSum += boxes[i];
}
return -1;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("请输入箱子上贴的数字列表,使用逗号分隔:");
String input = scanner.nextLine();
String[] boxStr = input.split(",");
int[] boxes = new int[boxStr.length];
for (int i = 0; i < boxStr.length; i++) {
boxes[i] = Integer.parseInt(boxStr[i]);
}
int goldBoxIndex = findGoldBox(boxes);
System.out.println("第一个黄金宝箱的编号为:" + goldBoxIndex);
}
}