所以我有一个整数数组。我正在尝试采用该数组并找到一个索引N,其中N左边的整数的总和等于N右边的整数的总和。如果没有索引可以使这种情况发生,请返回-1。
例如:
假设我有一个数组[1,2,3,4,3,2,1]
:我希望该方法返回索引3,因为在数组的第3个位置,索引左侧的总和与索引右侧的总和都等于6:
[1,2,3].sum #=> 6
[3,2,1].sum #=> 6
对于数组,[1,100,50,-51,1,1]
它应该返回索引1,因为在数组的第1个位置,索引左侧的总和与索引[1].sum
右侧的总和[50,-51,1,1].sum
都等于1。
最后一个:
我[20,10,-80,10,10,15,35]
在索引0处有一个数组,左边是[]
,右边是[10,-80,10,10,15,35]
。两者相加时等于0。(空数组等于0)。
索引0是左侧和右侧相等的地方。
假设数组都是长度在0到1000之间的整数,并且数字可以是正整数或负整数。
N的左侧等于N的右侧的最低索引N。如果它没有适合这些规则的索引,则返回-1。
如果一个数组有多个答案,它将返回最低的正确索引。我是这样开始的,但是我没有尝试给我想要的结果。
def find_even_index(arr)
if arr.size > 1
left_side = #some code to get left side #reduce(:+)
right_side = #some code to get right side #reduce(:+)
# something that gives index at which sum of left side is the same as right
elsif
# more than one result give lowest index
else
return -1
end
end
谢谢!
def eq_sum_index(arr)
right_sum = arr.sum
left_sum = 0
arr.each_with_index do |e, index|
right_sum -= e
return index if left_sum == right_sum
left_sum += e
end
-1
end
eq_sum_index([1, 2, 3, 4, 3, 2, 1])
# => 3
eq_sum_index([1, 100, 50, -51, 1, 1])
# => 1
eq_sum_index([20, 10, -80, 10, 10, 15, 35])
# => 0
解释:
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句