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.
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
/**
* @param Integer[] $nums
* @param Integer $target
* @return Integer[]
*/
// 12ms
function twoSum($nums, $target)
{
$arr = [];
foreach($nums as $k => $v) {
if(isset($arr[$v])) {
return [$arr[$v], $k];
} else {
$arr[$target-$v] = $k;
}
}
return [];
}
// 8ms
function twoSum($nums, $target) {
for ($i=0; $i<count($nums); $i++) {
$keys = [];
$start = $target - $nums[$i];
$temp = $nums;
array_splice($temp, $i, 1);
if(in_array($start, $temp)) {
$end = array_search($start, $nums);
if ($i == $end) {
unset($nums[$i]);
$end = array_search($start, $nums);
}
array_push($keys, $i);
array_push($keys, $end);
return $keys;
}
}
}
// 140ms
function twoSum($nums,$target){
$len = count($nums);
for ($i=0; $i < $len; $i++) {
if (in_array(($target-$nums[$i]),$nums)){
search_key = array_search(($target-$nums[$i]),$nums);
if($i==$search_key){
continue;
}
return [$i,$search_key];
}
}
return [];
}
// 64ms
func twoSum(nums []int, target int) []int {
var res []int
for i := 0; i < len(nums); i++ {
tmp := nums[i]
for j := i+1 ; j < len(nums) ; j++ {
if nums[j] + tmp == target {
res = append(res, i, j)
}
}
}
return res
}
// 4ms
func twoSum(nums []int, target int) []int {
m := make(map[int]int)
for i, n := range nums {
_, prs := m[n]
if prs {
return []int{m[n], i}
} else {
m[target-n] = i
}
}
return nil
}
// 4ms
func twoSum(nums []int, target int) []int {
m := make(map[int]int)
for i, v := range nums {
if j, ok := m[target - v]; ok {
return []int{j, i}
} else {
m[v] = i
}
}
return []int{-1, -1}
}
// 12ms
func twoSum(nums []int, target int) []int {
result := make([]int, 2)
num_index_map := make(map[int]int)
for i, num := range nums {
if idx, existed := num_index_map[target - num]; existed {
result[0] = idx
result[1] = i
return result
}
num_index_map[num] = i
}
return result
}
方法一
一般是自己实现的方法,其他方式
是在discuss
中查找的更为优秀的方法,用作学习和借鉴。