-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathSolution.php
46 lines (42 loc) · 1.03 KB
/
Solution.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
<?php
// https://leetcode.com/problems/two-sum/
class Solution
{
/**
* @param Integer[] $nums
* @param Integer $target
* @return Integer[]
*/
function twoSum3($nums, $target)
{
for ($i = 0; $i < count($nums); $i++) {
for ($j = $i + 1; $j < count($nums); $j++) {
if ($nums[$i] + $nums[$j] == $target) {
return [$i, $j];
}
}
}
}
function twoSum($nums, $target)
{
$len = count($nums);
$map = [];
for ($i = 0; $i < $len; $i++) {
$num = $nums[$i];
$solution = $target - $num;
if (isset($map[$solution]) && $map[$solution]['index'] != $i) {
return [$map[$solution]['index'], $i];
}
$map[$num] = [
'index' => $i,
'solution' => $solution
];
}
}
}
$nums = [2, 7, 11, 15];
$target = 9;
// [0,1]
$obj = new Solution();
$res = $obj->twoSum($nums, $target);
print_r($res);