php - 如果求和时单个数组两侧的值相等,则查找索引

标签 php arrays

我有一个白板问题,我认为它超出了我的技能范围,所以我什至不知道如何解决这个问题。

我想迭代每个值并对左侧/右侧的元素求和,如果它们相等则返回索引值。

所以:

[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_slicearray_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;
}

这一小段代码循环遍历整个数组,并对数组当前位置的左侧和右侧求和。比较结果,如果结果相同,则返回数组的键。

对于大型数组,您可以尝试使用 yieldIterator 实例来减少内存消耗。

关于php - 如果求和时单个数组两侧的值相等,则查找索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64447495/

相关文章:

php - 使用 symfony 和 MAMP 时 PDO 连接错误

JavaScript - 使用值作为元素名称推送 JSON 对象

javascript - 在具有相同 ID 的数组中添加/求和多个值

ruby - 在法拉第传递 url 参数数组

javascript - 删除具有键值的嵌套数组中的对象

javascript 从日期选择器获取日期而不是添加天数

javascript - if(isset... 在使用 javascript 加载 php 文件 onsubmit 时不起作用

php - 以逗号分隔的 HTML 表单输入字段

php - 如何替换不在链接标记内的字符串?

c++ - 此数组中的某些值无特殊原因变为零 (0)