两数之和
给定一个整数数组
nums和一个目标值target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。
示例:
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]方法一:暴力法(php)
class Solution {
/**
* @param Integer[] $nums
* @param Integer $target
* @return Integer[]
*/
function twoSum($nums, $target) {
$count = count($nums);
for ($i=0; $i<$count-1; $i++) {
for ($j=$i+1; $j<$count; $j++) {
if(($nums[$i] + $nums[$j]) == $target ){
return array($i,$j);
break;
}
}
}
}
}时间复杂度:O(n^2)
空间复杂度:O(1)
方法二:数组查找(php)
class Solution {
/**
* @param Integer[] $nums
* @param Integer $target
* @return Integer[]
*/
function twoSum($nums, $target) {
$count = count($nums);
for ($i=0; $i<$count-1; $i++) {
$tmp = $target - $nums[$i];
$newnums = $nums;
unset($newnums[$i]);
$res = array_search($tmp, $newnums);
if ($res !== false) {
return array($i,$res);
break;
}
}
}
}本来想用哈希表遍历,时间复杂度能降到O(n),但是没找到php实现的方法,最后用了array_search函数,比方法一稍微好一点,还可以继续优化

果博东方客服开户联系方式【182-8836-2750—】?薇- cxs20250806】
果博东方公司客服电话联系方式【182-8836-2750—】?薇- cxs20250806】
果博东方开户流程【182-8836-2750—】?薇- cxs20250806】
果博东方客服怎么联系【182-8836-2750—】?薇- cxs20250806】
2025年10月新盘 做第一批吃螃蟹的人coinsrore.com
新车新盘 嘎嘎稳 嘎嘎靠谱coinsrore.com
新车首发,新的一年,只带想赚米的人coinsrore.com
新盘 上车集合 留下 我要发发 立马进裙coinsrore.com
做了几十年的项目 我总结了最好的一个盘(纯干货)coinsrore.com
新车上路,只带前10个人coinsrore.com
新盘首开 新盘首开 征召客户!!!coinsrore.com
新项目准备上线,寻找志同道合的合作伙伴coinsrore.com
新车即将上线 真正的项目,期待你的参与coinsrore.com
新盘新项目,不再等待,现在就是最佳上车机会!coinsrore.com
新盘新盘 这个月刚上新盘 新车第一个吃螃蟹!coinsrore.com
美人鱼
嘿乔
渚北谜案
三个秘密
肥女孩
肝胆相照粤配
热血燃烧