題目內(nèi)容
貧如洗的樵夫阿里巴巴在去砍柴的路上,無意中發(fā)現(xiàn)了強(qiáng)盜集團(tuán)的藏寶地,藏寶地有編號從0~N的箱子每個箱子上面貼有一個數(shù)字箱子中可能有一個黃金寶箱。
黃金寶箱滿足排在它之前的所有箱子數(shù)字和等于排在它之后的所有箱子數(shù)字之和;
一個箱子左邊部分的數(shù)字和定義為0: 最后一個箱子右邊部分的數(shù)字和定義為0.
幫阿里巴巴找到黃金寶箱,輸出第一個滿足條件的黃金寶箱編號,如果不存在黃金寶箱,請返回-1。
輸入描述
箱子上貼的數(shù)字列表,使用逗號分隔,例如1,-1,0
寶箱的數(shù)量不小于1個,不超過10000 寶箱上貼的數(shù)值范圍不低于-1000,不超過1000
輸出描述
第一個黃金寶箱的編號
樣例
輸入
2,5,-1,8,6
輸出
3
說明
下標(biāo)3之前的數(shù)字和為:2+5+-1=6
下標(biāo)3之后的數(shù)字和為:6=6
輸入
8,9
輸出
-1
說明
不存在符合要求的位置
輸入
11
輸出
0
說明
下標(biāo)0之前的數(shù)字和為:0文章來源:http://www.zghlxwxcb.cn/news/detail-621109.html
下標(biāo)0之后的數(shù)字和為:0文章來源地址http://www.zghlxwxcb.cn/news/detail-621109.html
public class GoldChest {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int [] num = Arrays.stream(sc.nextLine().split(",")).mapToInt(Integer::parseInt).toArray();
if (num.length == 1){
System.out.println(0);
return;
}
int end = equal(num,1);
System.out.println(end);
}
//單指針+循環(huán)遍歷
public static int equal(int [] num, int i){
Boolean end = false;
while (!end && i < num.length) {
int before = 0;
int after = 0;
for (int j = 0; j < num.length; j++) {
if (j < i) {
before += num[j];
} else if (j > i) {
after += num[j];
}
}
if (before == after) {
end = true;
} else {
i++;
}
}
if (!end) {
return -1;
}
return i;
}
}
到了這里,關(guān)于華為OD機(jī)考--阿里巴巴黃金箱的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!