Given an integer array nums and a target value target, and ask you to identify the target value of the two integers in the array, and return to their array subscript.
You can assume that each input corresponds to only one answer. However, you can not re-use the same array element.
Example:
Given nums = [2, 7, 11, 15], target = 9
Because nums [0] + nums [1 ] = 2 + 7 = 9
is returned [0, 1]
Code I
other's
When using a minimum of 16ms, defeated 99.74 percent, cycle time, problem-solving ideas worth considering
V1 version takes 64ms, thanks to "not like a pig mighty" proposal
class Solution
{
/**
* @param Integer[] $nums
* @param Integer $target
* @return Integer[]
*/
public function twoSum(array $nums, $target)
{
$find = [];
$count = count($nums);
for ($i = 0; $i < $count; $i++) {
$value = $nums[$i];
if ($a = array_keys($find, ($target - $value))) {
return [$a[0], $i];
}
$find[$i] = $value;
}
}
}
V2 improved version, use array_key_exists
class Solution
{
/**
* @param Integer[] $nums
* @param Integer $target
* @return Integer[]
*/
public function twoSum($nums, $target)
{
$found = [];
$count = count($nums);
for ($i = 0; $i < $count; $i++) {
$diff = $target - $nums[$i];
if (array_key_exists($diff, $found)) {
return [$found[$diff], $i];
}
$found[$nums[$i]] = $i;
}
}
}