Erlo

00 | Two Sum

2019-05-23 20:03:16 发布   141 浏览  
页面报错/反馈
收藏 点赞

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 JAVA JS 小程序 Python SEO MySql 确认