-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtwoSum.py
More file actions
42 lines (31 loc) · 1.06 KB
/
Copy pathtwoSum.py
File metadata and controls
42 lines (31 loc) · 1.06 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#两数之和
def twoSum( nums, target):
n = len(nums)
for i in range(n):
for j in range(i+1, n):
if target == nums[i] + nums[j]:
return [i, j]
nums = [2, 4, 6]
target = 10
print(twoSum(nums, target))
#两数之和hash版本
def two_sum(nums, target):
# 创建一个哈希表(字典)来存储数组中的每个元素及其对应的索引
# 保存格式{'2':0, '4':1....}
num_to_index = {}
# 遍历数组
for index, num in enumerate(nums):
# 计算当前元素与目标值之差
complement = target - num
# 检查差值是否存在于哈希表中
if complement in num_to_index:
# 如果存在,返回当前元素的索引和差值对应的索引
return [num_to_index[complement], index]
else:
# 将当前元素及其索引存入哈希表
num_to_index[num] = index
# 如果没有找到符合条件的两个元素,返回空列表
return []
target = 25
nums = [2, 4, 6, 10, 12, 13]
print(two_sum(nums, target))