Skip to main content

1. 两数之和 [easy]

1. 两数之和 [easy]

2020-05-31

https://leetcode-cn.com/problems/two-sum/

image

  • second try

执行用时 :44 ms, 在所有 Python 提交中击败了64.50%的用户

内存消耗 :14 MB, 在所有 Python 提交中击败了6.17%的用户


class Solution(object):
def twoSum(self, nums, target):
"""
负数竟然也可以包括在内。。
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
cache = {}
for i, n in enumerate(nums):
required = target - n
if required in cache:
return [i, cache[required]]
cache[n] = i

  • first try

执行用时 : 5396 ms 内存消耗 : 13.3 MB

class Solution(object):
def twoSum(self, nums, target):
"""
负数竟然也可以包括在内。。
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
for i, n in enumerate(nums):
for j, m in enumerate(nums):
if(i == j):
continue
if(m + n == target):
return [i, j]