系列文章目录
提示:这里可以添加系列文章的所有文章的目录,目录需要自己手动添加
例如:第一章 Python 机器学习入门之pandas的使用
提示:写完文章后,目录可以自动生成,如何生成可参考右边的帮助文档
文章目录
关键词
enumerate(nums)
题目
0001.两数之和
提示:以下是本篇文章正文内容,下面案例可供参考
1.第一次(20220906)
1.1.Leetcode
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
for i in range(len(nums)):
for j in range(i+1,len(nums)):
if nums[i]+nums[j]==target:
m=i
n=j
return [m,n]
1.2.Pycharm
from typing import List
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
records = dict()
# 用枚举更方便,就不需要通过索引再去取当前位置的值
for idx, val in enumerate(nums):
if target - val not in records:
records[val] = idx
else:
return [records[target - val], idx] # 如果存在就返回字典记录索引和当前索引
# if __name__ == '__main__':
# nums = [2, 7, 11, 15]
# target = 9
# solution = Solution()
# print(Solution.twoSum(nums, target))
nums = [2, 7, 11, 15]
target = 9
print(Solution.twoSum(self='',nums= nums, target= target))
1.3.结果
时间复杂度为O(n^2)
![在这里插入图片描述](https://img-blog.csdnimg.cn/5d9fdd42416d4f929bab77013ed4d880.png
2.第二次(20220906)
2.1.Leetcode
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
#old_nums = nums[:]
for i in range(len(nums)):
if (target - nums[i]) in nums[i+1:]:
return [i,nums[i+1:].index(target-nums[i])+i+1]
2.2.Pycharm
from typing import List
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
#old_nums = nums[:]
for i in range(len(nums)):
if (target - nums[i]) in nums[i+1:]:
return [i,nums[i+1:].index(target-nums[i])+i+1]
# if __name__ == '__main__':
# nums = [2, 7, 11, 15]
# target = 9
# solution = Solution()
# print(Solution.twoSum(nums, target))
# nums = [2, 7, 11, 15]
# target = 9
nums = [3,3]
target = 6
print(Solution.twoSum(self='',nums= nums, target= target))
2.3.结果
3.神犇答案
3.1.Leetcode
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
records = dict()
# 用枚举更方便,就不需要通过索引再去取当前位置的值
for idx, val in enumerate(nums):
if target - val not in records:
records[val] = idx
else:
return [records[target - val], idx] # 如果存在就返回字典记录索引和当前索引
3.2.Pycharm
from typing import List
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
records = dict()
#print(records)
#print(enumerate(nums))
# 用枚举更方便,就不需要通过索引再去取当前位置的值
for idx, val in enumerate(nums):
if target - val not in records:
if target - val not in records:
records[val] = idx
else:
return [records[target - val], idx] # 如果存在就返回字典记录索引和当前索引
# if __name__ == '__main__':
# nums = [2, 7, 11, 15]
# target = 9
# solution = Solution()
# print(Solution.twoSum(nums, target))
# nums = [2, 7, 11, 15]
# target = 9
nums = [3,3]
target = 6
print(Solution.twoSum(self='',nums= nums, target= target))
3.3.结果
复杂度为O(n)