【发布时间】:2021-05-25 22:14:03
【问题描述】:
所以我有一个整数数组。我正在尝试获取该数组并找到一个索引 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].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
谢谢!
【问题讨论】:
标签: arrays ruby indexing methods split