找到一个索引在阵列给出之前和之后它的总和?它的、阵列、总和、索引

2023-09-11 07:11:31 作者:夕阳、坠落的很沧桑

由于一个数组,我想找到一个指数,它面前的数字,这些数字后,给予同等金额。

Given an array, I would like to find an index, that the numbers before it, and the numbers after it gives equal sum.

例如像数组 [4,5,6,11,7,8]

输出指数 3 ,因为 4 + 5 + 6 = 7 + 8

推荐答案

首先找到的所有项目相加,将其保存为,然后从阵列和金额开始阅读达项目到达(sum-当前索引值)/ 2 ,如果你没有得到这样的结果,表示没有这样的索引,如果你还得到总之/ 2次迭代的各项指标,意味着相关的指标就是你的答案。

First find sum of all items, save it as sum, then read from start of array and sum up items to arrive to (sum- current index value)/2, if you didn't get such result, means there isn't such an index, also if you get sum/2 in each index of iteration, means related index is your answer.

示例: 4,5,6,11,7,8 总和= 41。

Sample: 4,5,6,11,7,8 sum = 41.

check index 0: currentSum  = 4, currentSum - currentValue = 4-4 != (41 - 4)/2
check index 1: currentSum  =  9, currentSum - currentValue = 9-5 != (41 - 5)/2
check index 2: currentSum  = 15, currentSum - currentValue = 15-9 != (41 - 9)/2
check index 3: currentSum  = 26, currentSum - currentValue = 15 == (41 - 11)/2