leetcode刷题之第一题:两数之和(python)

leetcode刷题之第一题:两数之和
题目:给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。
示例
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
使用dict模拟hash结构
解法一
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
idxDict = dict()
for idx, num in enumerate(nums):
if target - num in idxDict:
return [idxDict[target - num], idx]
idxDict[num] = idx #将索引index赋予对应的值
解法二
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
hashmap={}
for ind,num in enumerate(nums):
hashmap[num] = ind #将索引index赋予对应的值
for i,num in enumerate(nums):
j = hashmap.get(target - num)
if j is not None and i!=j and i<j:
print(i,j)

自己的解法:
普通解法,用时较长,直接搜索target-num在num的右边有没有
注意index函数的用法
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
lens = len(nums)
j=0
for i in range(0,lens):
temp = nums[i]
if target-temp in nums[i+1:]:
j=nums.index(target-temp,i+1)**
if i<j:
return i,j

发布了3 篇原创文章 · 获赞 0 · 访问量 212

猜你喜欢

转载自blog.csdn.net/qq_44854885/article/details/102932435