暴力解决:
#暴力
from typing import List
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
p=0
lens=len(nums)
for i in range(lens):
for j in range(i+1,lens):
if nums[i]+nums[j] == target:
p=1
return [i,j]
if p == 0:
return []
if __name__ == '__main__':
c=Solution()
s=c.twoSum([2,7,8,11],9)
print(s)
利用哈希表:
#哈希表
from typing import List
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
hashmap={} #建立一个哈希表
for ind,num in enumerate(nums):
hashmap[num]=ind
print(hashmap)
for i,num in enumerate(nums):
j=hashmap.get(target-num)
if j!=None and j!=i:
return [i,j]
if __name__ == '__main__':
c=Solution()
s=c.twoSum([2,7,8,11],9)
print(s)