原题目是这样的: 给定一个整数数组和一个目标值, 找出数组中和为目标值的两个数. 你可以假设每个输入只对应一种答案, 且同样的元素不能被重复利用.
eg: 给定 nums = [2, 7, 11, 15], target = 9 因为 nums[0] + nums[1] = 2 + 7 = 9 所以返回 [0, 1];
测试写了一个比较 low 的, 简单粗暴, 代码如下:
- 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);
测试结果 array(1,4), 主要思路就是遍历数组中每一个数字, 在数组中, 看它与自己之后的数字相加是否等于 target.
来源: http://www.bubuko.com/infodetail-2757232.html