Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

哈希表两个数之和,直接在列表上进行操作,python语言 #2744

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions two-sum.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
# -*coding=utf-8 -*-
# @Time : 2024/9/21 10:08
# @Author : 杨楠
# @File : two-sum.py
# @Software: PyCharm
class Solution(object):
def twoSum(self,nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
# 直接在列表上进行哈希表操作
for i in range(len(nums)):
a = target - nums[i]
try:
position = nums.index(a)
except ValueError:
pass
else:
if position != i:
return [i,position]


nums = [-1,-2,-3,-4,-5]
target = -8
print(twoSum(nums, target))