题目

给定一个整数数组, 返回其中两个数的索引号, 使得这两个数相加等于另一个特定的数.

假设对于每一个输入, 只有一个正确的解, 而且同一个元素不能使用两次.

比如:

给定 nums = [2, 7, 11, 15], 相加结果 target = 9
因为: nums[0] + nums[1] = 2 + 7 = 9
所以解应该是 [0, 1]

思路

(略.)

代码

Python3 (未接受)

1
2
3
4
5
6
7
8
class Solution:
def twoSum(self, nums, target):
length = len(nums)
for i in range(0, length):
for j in range(i+1, length):
if nums[i] + nums[j] == target:
return [i, j]
return None

Go

1
2
3
4
5
6
7
8
9
10
func twoSum(nums []int, target int) []int {
for i, v1 := range(nums) {
for j, v2 := range(nums[i+1:]) {
if v1 + v2 == target {
return []int{i, j+i+1}
}
}
}
return nil
}

Python3

1
2
3
4
5
6
7
8
class Solution:
def twoSum(self, nums, target):
m = {}
for (i, v) in enumerate(nums):
if m.get(target-v) is not None:
return [m[target-v], i]
m[v] = i
return None

Go

1
2
3
4
5
6
7
8
9
10
func twoSum(nums []int, target int) []int {
m := make(map[int]int)
for i, v := range(nums) {
if i1, ok := m[target-v]; ok {
return []int{i1, i}
}
m[v] = i
}
return nil
}