1、两数之和

  1. 题目
  2. 解答

题目

给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。

你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。

示例:

1
2
3
4
给定 nums = [2, 7, 11, 15], target = 9

因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]

解答

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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
###------------------------2、库导入------------------------###
import time
import datetime
# from memory_profiler import profile
###------------------------3、参数配置------------------------###
nums = [2,7,11, 15]
target = 9
###------------------------4、主体程序------------------------###
class Solution:

def twoSum(self, nums, target):
'''
方法1
:param nums:
:param target:
:return:
'''
hashmap={}
# 时间复杂度 O(n)
for ind,num in enumerate(nums):
hashmap[num] = ind
print(hashmap)
# 时间复杂度 O(n)
for i,num in enumerate(nums):
# 时间复杂度 O(n)
j = hashmap.get(target - num)
if j is not None and i!=j:
return [i,j]
# 总的时间复杂度 O(n^2)

# @profile()
def twoSum2(self, nums, target):
'''
方法2
:param nums:
:param target:
:return:
'''
le = len(nums)
for i in range(le):
j = i + 1
while 1:
if (nums[i] + nums[j]) == target:
return i, j
else:
j += 1
if j >= le:
break


solut = Solution()
start = time.perf_counter()
out = solut.twoSum(nums, target)
end = time.perf_counter()
print("out is", out)
print("time is", end-start)

微信:宏沉一笑
公众号:漫步之行

签名:Smile every day
名字:宏沉一笑
邮箱:whghcyx@outlook.com
个人网站:https://whg555.github.io


转载请注明来源,欢迎对文章中的引用来源进行考证,欢迎指出任何有错误或不够清晰的表达。可以在下面评论区评论,也可以邮件至 whghcyx@outlook.com

文章标题:1、两数之和

文章字数:328

本文作者:宏沉一笑

发布时间:2020-08-17, 00:00:00

最后更新:2023-06-19, 13:58:36

原始链接:https://whghcyx.gitee.io/2020/08/17/IT-2020-8-17-1%E3%80%81%E4%B8%A4%E6%95%B0%E4%B9%8B%E5%92%8C/

版权声明: "署名-非商用-相同方式共享 4.0" 转载请保留原文链接及作者。

目录
×

喜欢就点赞,疼爱就打赏