00 | Two Sum
程序员文章站
2022-04-28 15:37:17
Question Given an array of integers, return indices of the two numbers such that they add up to a specific target. You may assume that each input woul ......
question
given an array of integers, return indices of the two numbers such that they add up to a specific target.
you may assume that each input would have exactly one solution, and you may not use the same element twice.
example:
given nums = [2, 7, 11, 15], target = 9, because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1].
answer
1 class solution { 2 3 /** 4 * @param integer[] $nums 5 * @param integer $target 6 * @return integer[] 7 */ 8 public function twosum($nums, $target) { 9 $res = []; 10 for($i=0; $i<count($nums); $i++) { 11 for($j=$i+1; $j<count($nums); $j++) { 12 if($nums[$i]+$nums[$j] === $target) { 13 array_push($res, $i); 14 array_push($res, $j); 15 } else { 16 continue; 17 } 18 } 19 } 20 return $res; 21 } 22 }
这是我想到的方案,the least efficient solution.
上一篇: 【php设计模式】单例模式
推荐阅读
-
Oracle中的SUM用法讲解
-
PHP计算数组中值的和与乘积的方法(array_sum与array_product函数)
-
苹果表Apple Watch 4月10日凌晨00:01开始接受预定 各地具体时间汇总
-
Oracle中的SUM用法讲解
-
小米超薄5000mAh移动电源今日12:00开卖:49元/无需预约
-
小米超薄5000mAh移动电源今日12:00开卖:49元/无需预约
-
199元小米小盒子购买地址在哪? 今天中午12:00开卖
-
java中计算字符串长度的方法及u4E00与u9FBB的认识
-
小米蓝牙耳机发布 售价79元 6月18日10:00 开卖
-
sum(case when then)(判断男女生的个数)