leetcode 两数之和 Python 求解答

2018-06-29 14:02:04 +08:00
 a476286557

给定一个整数数组和一个目标值,找出数组中和为目标值的两个数。

你可以假设每个输入只对应一种答案,且同样的元素不能被重复利用。

示例:

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

因为 nums[0] + nums[1] = 2 + 7 = 9 所以返回 [0, 1] 我写的代码如下:
class Solution:
    def twoSum(self, nums, target):
    """
    :type nums: List[int]
    :type target: int
    :rtype: List[int]
    """
    list = []
    for i in nums:
        a = target - i
        if a != i:
            if a in nums:
                index1 = nums.index(i)
                list.append(index1)

我想问问为这个为什么不对?谢谢

3948 次点击
所在节点    Python
24 条回复
IceCola1
2018-06-30 00:22:22 +08:00
你们的都好长啊,我这个 44ms
swulling
2018-06-30 06:59:54 +08:00
标准答案哈希表,On
ayyll
2018-06-30 08:24:30 +08:00
@swulling 楼上一堆暴力。。这题哈希应该不难想到吧。。。。
huanyouchen
2018-06-30 20:43:57 +08:00
通过字典构建一个哈希表:
class Solution:
def twoSum(self, nums, target):
dic = {}
for i,num in enumerate(nums):
if num in dic:
return [dic[num],i]
else:
dic[target-num] = i

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/466856

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX