题目要求:
- 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的 两个 整数。
- 你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。
小白学python,基础的语法已懂,但不太会操作,所以补上所需知识点~
1. tuple
tuple是一种list,但与list有区别的是tuple不可变。因此,tuple也可以用切片操作,只是操作的结果仍是tuple。
(0,1,2,3,4,5)[:3]
(0, 1, 2)
2.列表生成式
列表生成式即List Comprehensions,是Python内置的非常简单却强大的可以用来创建list的生成式。举个?,要生成list [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]可以用list(range(1, 11)):
list(range(1,11))
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
作为一个萌新、小白、掉包小贼,接下来主要还是要学习算法啦o( ̄▽ ̄)o
大约有三种思路!
- 解法一:求差值法
class Solution:
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
n = len(nums)
for i in range(n):
x = target - nums[i]
if x in nums:
y = nums.index(x)
if y!=i:
return i,y
逃不开的循环,假定i在,那么target-i若在,取下标~
- 解法二:直接循环
class Solution:
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
n = len(nums)
#x取值从0到n
for x in range(n):
#y取值从x+1到n
for y in range(x+1,n):
if nums[y] == target - nums[x]:
return x,y
- 解法三:求差值,并使用字典求解
class Solution:
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
n =len(nums)
#创建一个空字典
dict ={}
for x in range(n):
a = target - nums[x]
#判断字典中是否存在nums[x],不存在向其中增加键值对
if nums[x] in dict:
return dict[nums[x]],x
else:
dict[a]=x #修改x对应的值为a
▶分析三种算法的时间复杂度,空间复杂度:
算法分析 | 解法 | 时间复杂度 | 空间复杂度 |
---|---|---|---|
解法一 | O(n*2) | O(1) | |
解法二 | O(n*2) | O(1) | |
解法三 | O(1) | O(n) |