LeetCode 第1题：Two Sum

pktangyue · · 618 次点击 · · 开始浏览

题目

``````给出 nums = [2, 7, 11, 15], target = 9,

``````

Go 实现

``````func twoSum(nums []int, target int) []int {
h := make(map[int]int)
for i, value := range nums {
if wanted, ok := h[value]; ok {
return []int{wanted, i}
} else {
h[target-value] = i
}
}
return nil
}
``````

Python3 重写

``````class Solution:
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
h = {}
for i, value in enumerate(nums):
if value in h:
return [h[value], i]
else:
h[target - value] = i
return None
``````

Python3 优化

``````class Solution:
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
h = {}
for i in range(len(nums)):
value = nums[i]
if value in h:
return [h[value], i]
else:
h[target - value] = i
return None
``````

0 回复

• 请尽量让自己的回复能够对别人有帮助
• 支持 Markdown 格式, **粗体**、~~删除线~~、``单行代码``
• 支持 @ 本站用户；支持表情（输入 : 提示），见 Emoji cheat sheet
• 图片支持拖拽、截图粘贴等方式上传

题目

``````给出 nums = [2, 7, 11, 15], target = 9,

``````

Go 实现

``````func twoSum(nums []int, target int) []int {
h := make(map[int]int)
for i, value := range nums {
if wanted, ok := h[value]; ok {
return []int{wanted, i}
} else {
h[target-value] = i
}
}
return nil
}
``````

Python3 重写

``````class Solution:
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
h = {}
for i, value in enumerate(nums):
if value in h:
return [h[value], i]
else:
h[target - value] = i
return None
``````

Python3 优化

``````class Solution:
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
h = {}
for i in range(len(nums)):
value = nums[i]
if value in h:
return [h[value], i]
else:
h[target - value] = i
return None
``````