RuslanHeorhiiev

Solution 1.1.1

Jun 18th, 2020
217
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 2.11 KB | None | 0 0
  1. /**
  2.  * Класс линейной реализации
  3.  */
  4. class Solution {
  5.    
  6.     /**
  7.      * Integer[] массив значений
  8.      */
  9.     private $nums;
  10.    
  11.     /**
  12.      * Integer искомая сумма
  13.      */    
  14.     private $target;
  15.    
  16.        
  17.     /**
  18.      * Возвращает ключи суммы
  19.      *
  20.      * @param Integer[] $nums
  21.      * @param Integer $target
  22.      * @return Integer[]
  23.      */    
  24.     public function twoSum(array $nums,  int $target) {
  25.         $this->target = $target;
  26.         $this->nums   = $nums;
  27.                
  28.         return $this->getKeys();
  29.     }    
  30.    
  31.    
  32.     /**
  33.      * Возвращает ключи суммы
  34.      * метод рекурсивно вызывается
  35.      */
  36.     private function getKeys() {
  37.         if (2 > count($this->nums)) {
  38.             return [];
  39.         }
  40.                
  41.         $first = $this->extractNumsFirst();
  42.            
  43.         foreach ($this->nums as $key => $value) {
  44.             $sum = $first['value'] + $value;            
  45.                
  46.             if ($sum == $this->target) {
  47.                 return [
  48.                     $first['key'],
  49.                     $key
  50.                 ];
  51.             }
  52.         }        
  53.        
  54.         return $this->getKeys();            
  55.     }
  56.    
  57.    
  58.     /**
  59.      * Извлечь первый элемент
  60.      */
  61.     private function extractNumsFirst() {
  62.         reset($this->nums);
  63.        
  64.         $key = key($this->nums);
  65.         $val = $this->nums[$key];
  66.        
  67.         unset($this->nums[$key]);
  68.        
  69.         return [
  70.             'key'   => $key,
  71.             'value' => $val,
  72.         ];
  73.     }
  74. }
Advertisement
Add Comment
Please, Sign In to add comment