我有一个白板问题,我认为它超出了我的技能范围,所以我什至不知道如何解决这个问题。
我想迭代每个值并对左侧/右侧的元素求和,如果它们相等则返回索引值。
所以:
[1, 2, 3, 4, 3, 2, 1]; // return 3
官方问题:
You are going to be given an array of integers. Your job is to take that array and find an index N where the sum of the integers to the left of N is equal to the sum of the integers to the right of N. If there is no index that would make this happen, return -1.
有好心人可以帮帮我吗?我查看了 array_map()
和 array_filter()
,虽然很有帮助,但我想不出在迭代数组时如何在当前索引之间来回遍历。
最佳答案
这可以通过对数组的整个范围进行简单的 for 循环并结合 array_slice
和 array_sum
来完成。
function doSomething(array $data): int {
for ($i = 0, $count = count($data); $i < $count; $i++) {
$left = $i > 0 ? array_slice($data, 0, $i) : [ $data[0] ];
$right = $i > 0 ? array_slice($data, $i + 1) : $data;
$left_result = array_sum($left);
$right_result = array_sum($right);
if ($left_result === $right_result) {
return $i;
}
}
return -1;
}
这一小段代码循环遍历整个数组,并对数组当前位置的左侧和右侧求和。比较结果,如果结果相同,则返回数组的键。
对于大型数组,您可以尝试使用 yield
或 Iterator
实例来减少内存消耗。
关于php - 如果求和时单个数组两侧的值相等,则查找索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64447495/