Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- $inputArray = [1, 6, 3, 10, 2, 4, 3, 22, 10, 11, 4, 2, 7, 8];
- $solution = new Solution();
- echo 'Result: ';
- print_r( $solution->twoSum($inputArray, 8) );
- /**
- * Класс линейной реализации
- */
- class Solution {
- /**
- * Integer[] массив значений
- */
- private $nums;
- /**
- * Integer искомая сумма
- */
- private $target;
- /**
- * Возвращает ключи суммы
- *
- * @param Integer[] $nums
- * @param Integer $target
- * @return Integer[]
- */
- public function twoSum(array $nums, int $target) {
- $this->target = $target;
- // исключить ненужные элементы
- $this->nums = array_filter($nums, function($value) use ($target) {
- return ((int)$value && $value < $target);
- });
- return $this->getKeys();
- }
- /**
- * Возвращает ключи суммы
- * метод рекурсивно вызывается
- */
- private function getKeys() {
- if (2 > count($this->nums)) {
- return [];
- }
- $first = $this->extractNumsFirst();
- foreach ($this->nums as $key => $value) {
- $sum = $first['value'] + $value;
- if ($sum == $this->target) {
- return [
- $first['key'],
- $key
- ];
- }
- }
- return $this->getKeys();
- }
- /**
- * Извлечь первый элемент
- */
- private function extractNumsFirst() {
- reset($this->nums);
- $key = key($this->nums);
- $val = $this->nums[$key];
- unset($this->nums[$key]);
- return [
- 'key' => $key,
- 'value' => $val,
- ];
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment