找到一个索引在阵列给出之前和之后它的总和? [英] finding an index in array the gives a sum before and after it?

查看:107
本文介绍了找到一个索引在阵列给出之前和之后它的总和?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

这篇关于找到一个索引在阵列给出之前和之后它的总和?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆