2021.01.04
leetcode刷题《hello world》
由于疫情的原因,实在无聊,便开始了LeetCode刷题,以来为了进一步提高自己的编程能力,而来为了打发一下这实在无聊的隔离时光。
第一步在自己的pycharm中配置LeetCode好插件,具体方法请参考这篇文章
第二步开始敲代码吧!
方法一:暴力求解(双指针)
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
for i in range(len(nums)):
for j in range(i+1,len(nums)):
if nums[i]+nums[j]==target:
return [i,j]
方法二:hashmap(哈希表)
优势在于只需要遍历一遍,计算量比较小
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
hashmap={}
for i in range(len(nums)):
if target-nums[i] in hashmap.keys():
return [target-nums[i],nums[i]]
else:
hashmap[nums[i]]=i