RuslanHeorhiiev

Solution 1.1

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