1 <?php 2 #查找有序数组中和为n的数对 3 #思路是从数组两边开始找,当a[h] + a[t] == n,返回数对 4 #当a[h] + a[t] < n, h++ 5 #当a[h] + a[t] > n, t-- 6 7 function search_n($a, $n) { 8 $h = 0; 9 $t = count($a) - 1; 10 $pairs = array(); 11 12 while ($h < $t) { 13 $sum = $a[$h] + $a[$t]; 14 if ($n == $sum) { 15 $pairs[$a[$h]] = $a[$t]; 16 #此处不保存重复的数对,所以首尾坐标同时改变 17 $h++; 18 $t--; 19 } else if ($n > $sum) { 20 $h++; 21 } else { 22 $t--; 23 } 24 } 25 26 return $pairs; 27 } 28 29 #如果数组非有序,可以先用堆排序排序一次 30 $a = array(1, 5, 7, 9, 10, 11, 12, 13, 15, 18, 19); 31 $n = 20; 32 print_r(search_n($a, $n)); 33 ?>
Array ( [1] => 19 [5] => 15 [7] => 13 [9] => 11 )