Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * Класс линейной реализации
- */
- 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 = $nums;
- 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