The original topic is this: given an array of integers and a target value, find the two numbers in the array and the target values. You can assume that each input corresponds to only one answer, and that the same element cannot be reused.
Eg: Given nums = [2, 7, 11, 15], target = 9 because nums[0] + nums[1] = 2 + 7 = 9 so return [0, 1];
The test wrote a relatively low, simple and rude, the code is as follows:
class test
{
function __construct()
{
echo "邱二狗<br>";
}
public function a1($arr,$target)
{
$length = count($arr);
for ($i=0; $i < $length ; $i++)
{
for ($j=$i+1; $j < $length ; $j++)
{
if ($arr[$i]+$arr[$j] == $target)
{
$b=array($i,$j);
var_dump($b);
return $b;
}
}
}
}
}
$hc = new test();
$hc->a1(array(2,3,4,5,6),9);
The test result Array (1,4), the main idea is to iterate over each number in the array, in the array, see if it and its own number after the addition is equal to target.
PHP (1) "Sum of two numbers" algorithm problem