Created
September 5, 2019 20:32
-
-
Save dasider41/dd67c14ee5314a0c5c01f3a671109e48 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/* | |
https://leetcode.com/problems/two-sum/submissions/ | |
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]. | |
*/ | |
function twoSum(array $nums, int $target): array | |
{ | |
$length = count($nums) - 1; | |
for ($i = 0; $i <= $length; $i++) { | |
for ($j = $i + 1; $j <= $length; $j++) { | |
$sumResult = $nums[$i] + $nums[$j]; | |
if ($sumResult === $target) { | |
return [$i, $j]; | |
} | |
} | |
} | |
return []; | |
} | |
// /Test code 1 | |
$nums = [2, 7, 11, 15]; | |
$target = 9; | |
var_dump(twoSum($nums, $target) === [0, 1]); | |
// /Test code 2 | |
$nums = [3, 2, 4]; | |
$target = 6; | |
var_dump(twoSum($nums, $target) === [1, 2]); | |
// /Test code 3 | |
$nums = [2, 5, 5, 11]; | |
$target = 10; | |
var_dump(twoSum($nums, $target) === [1, 2]); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
class Solution {
}